How do I Implement Xamarin.Essentials in my Unit Testing? - unit-testing

I want to execute a unit test on my GetById method that is using a local file storage as the source.
When I debug the test I get the following error in my service:
Xamarin.Essentials.NotImplementedInReferenceAssemblyException: 'This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.'
I do not have this error when I run the application.
The service itself uses xamarin.essentials.
I've installed the N.P. in my test project as well.. Still no luck.
Below you can find my code and a screenshot of where the error takes place in my service.
Thanks in advance for the help!
using Imi.Project.Mobile.Domain.Models;
using Imi.Project.Mobile.Domain.Services.Interfaces;
using Imi.Project.Mobile.Domain.Services.Local;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Newtonsoft.Json;
using System.IO;
using Xamarin.Essentials;
namespace Imi.Project.Mobile.Tests
{
public class LocalProductionOrderServiceTests
{
ProductionOrder[] testProductionOrders;
public LocalProductionOrderServiceTests()
{
testProductionOrders = ProductionOrdersTestData.testProductionOrders;
}
[Fact]
public async void GetById_Returns_ProductionOrderWithCorrectId()
{
//arrange
var testProductionOrder = testProductionOrders[0];
var mockService = new Mock<IProductionOrderService>();
mockService.Setup(service => service.GetById(testProductionOrder.Id)).Returns(Task.FromResult(testProductionOrder));
var productionOrderService = new LocalProductionOrderService();
//act
var productionOrderById = await productionOrderService.GetById(testProductionOrder.Id);
//assert
Assert.NotNull(productionOrderById);
Assert.Equal(testProductionOrder.Id.ToString(), productionOrderById.Id.ToString());
}
}
}

Related

Is there any way of checking if a website is using a 3rd party cookie?

I have a list of websites that i have to check if there are any 3rd party cookies.
And going through everyone one of them an checking is not the smartest way of doing it..
Does any one know any solution of checking a hand full of links ?
If anyone has any idea let me know please.
I'm not sure if you need any more informations.
Thinking VSCode + Nunit + Selenium might be a pretty quick way to pop open a browser and confirm your cookies. https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-nunit
pair that with some code like:
namespace YourProject
{
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
[TestFixture]
class Chrome
{
private IWebDriver driver;
[SetUp]
public void StartTest()
{
driver = new ChromeDriver();
}
[TearDown]
public void EndTest()
{
driver.Close();
driver.Quit();
}
[Test]
public void CheckAllSiteCookies()
{
driver.Navigate().GoToUrl("http://<YourFirstWebsite>");
CookieCheck(cookieInfo);
driver.Navigate().GoToUrl("http://<YourSecondWebsite>");
CookieCheck(cookieInfo);
driver.Navigate().GoToUrl("http://<YourThirdWebsite>");
CookieCheck(cookieInfo);
driver.Navigate().GoToUrl("http://<YourFourthWebsite>");
CookieCheck(cookieInfo);
}
public void CookieCheck(string cookieInfo)
{
// C# example provided here for reading cookies
// https://www.guru99.com/handling-cookies-selenium-webdriver.html
}
}
}

Can not run Unitests with Xamarin

I want to check my Xamarin project code (Cookbook) with unit tests. I've created a Unitest for Xamarin project from Visual Studio (UITest1). When I try to run it the linker writes the following error:
Error NU1201 Project Cookbook is not compatible with net461 (.NETFramework,Version=v4.6.1) / win-x64. Project Cookbook supports: monoandroid81 (MonoAndroid,Version=v8.1) UITest1
What am i doing wrong? Tried to Google but with no luck.
This is the Uinitests code if it helps:
using System;
using System.IO;
using System.Linq;
using Cookbook;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
namespace UITest1
{
[TestFixture(Platform.Android)]
[TestFixture(Platform.iOS)]
public class Tests
{
IApp app;
Platform platform;
private Ingredient ingr;
public Tests(Platform platform)
{
this.platform = platform;
}
[SetUp]
public void BeforeEachTest()
{
//app = AppInitializer.StartApp(platform);
ingr = new Ingredient();
}
[Test]
public void WelcomeTextIsDisplayed()
{
AppResult[] results = app.WaitForElement(c => c.Marked("Welcome to Xamarin.Forms!"));
app.Screenshot("Welcome screen.");
Assert.IsTrue(results.Any());
}
[Test]
public void ParseFromString()
{
Ingredient ingr = new Ingredient();
ingr.TryToParseFromString("Ingredients");
Assert.AreEqual(0, ingr.Amount, "amount problem");
Assert.AreEqual(null, ingr.Item, "item problem");
Assert.AreEqual(null, ingr.Units, "units problem");
Assert.AreEqual("Ingredients", ingr.Unparsed, "unparsed problem");
}
I see that you're mixing up the concept of unit tests and UI tests since you have both in your test project. What you should do is create two separate projects, for example Cookbook.UITests and Cookbook.UnitTests. The reason is that UI Tests are meant to emulate user behavior while being run on an emulator, real device or perhaps a cloud testing service. Unit tests, on the other hand, should test stuff like the business logic of your code application (to put it simply).
What I would suggest you to do is the following:
Create the two separate projects Cookbook.UITests and Cookbook.UnitTests
Follow the great guidance by SushiHangover on how to set up the unit test project.
Follow the official documentation by Microsoft to set up the UITest project.

NUnit Test Adapter: Group by Class broken with named test cases (VS 2012)

Consider the following test fixture:
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace NUnitDemo
{
[TestFixture]
public class FooTests
{
public IEnumerable<TestCaseData> FooTestCases
{
get
{
yield return new TestCaseData(1).SetName("Once");
yield return new TestCaseData(2).SetName("Twice");
yield return new TestCaseData(3).SetName("Thrice");
yield return new TestCaseData(19140101).SetName("1914.01.02");
}
}
[TestCaseSource("FooTestCases")]
public void FooTest(int v)
{
}
}
}
With the NUnit Test Adapter (2.6) on Visual Studio 2012, Test Explorer grouped by class displays the following:
A little experimentation shows that this odd behaviour is invoked when the test name contains more than one dot. In this case, the class name is incorrectly replaced with the second-last section of the test-name, split on dot.
Is there any way to work around this issue?
I have 582 test cases in my project - most of them are named, parametrised tests.
To be honest, what I really want is the ability to organise my tests by fully-qualified class and method name, then by test-case name. The NUnit GUI does this in a rather clunky way but I am looking for integration into Visual Studio.

Windows Store App Unit Testing a USB device

I'm writing a USB device API for Windows Store Apps that uses Windows.Devices.USB API from Windows 8.1 to connect and communicate with the custom USB device. I'm using the Visual Studio 2013 dev preview IDE.
The following function in the library is used to connect to the USB device.
(Simplified for clarity)
public static async Task<string> ConnectUSB()
{
string deviceId = string.Empty;
string result = UsbDevice.GetDeviceSelector(new Guid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"));
var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(result, null);
if (myDevices.Count > 0)
{
deviceId = myDevices[0].Id;
}
UsbDevice usbDevice = null;
try
{
usbDevice = await UsbDevice.FromIdAsync(deviceId);
}
catch (Exception)
{
throw;
}
if (usbDevice != null)
return "Connected";
return string.Empty;
}
When called from the Windows Store App project, this function connects to the device flawlessly. However, when called from the Unit Test Library for Windows Store Apps project, the statement in the try block throws an exception.
A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
from what I've looked around, this happens when an Async function is called without the await keyword. But I'm using the await keyword alright!
Some more info, I am unable to use NUnit to write unit tests for Store Apps so am using the MSTest Framework.
[TestClass]
public class UnitTest1
{
[TestMethod]
public async Task TestMethod1()
{
await ConnectToUSB.ConnectUSB();
}
}
Also, I've included the following capability tags in the manifest files of both the App store projects too without which it's impossible for the Store Apps to connect to devices.
<m2:DeviceCapability Name="usb">
<m2:Device Id="vidpid:ZZZZ XXXX">
<m2:Function Type="name:vendorSpecific" />
</m2:Device>
</m2:DeviceCapability>
Is there something I'm missing or is this a bug in the MSTest Framework?
I think the problem is that
await UsbDevice.FromIdAsync(deviceId);
must be called on the UI thread because the app has to ask the user for access.
You have to CoreDispatcher.RunAsync to ensure you're on the UI thread or actually be in the code behind for a page.
I had the same problem with Unit Test App (Universal Windows) in VS 2017.
I verify answer of my predecessor Greg Gorman(see below). And I found this is true.
If you uses inside method body this construct:
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
async () =>
{
...
UsbDevice usbDevice = await UsbDevice.FromIdAsync(deviceId);
...
}).AsTask().Wait();
the FromIDAsync will work as you expect.
For your example change the test method to this:
[TestClass]
public class UnitTest1
{
[TestMethod]
public async Task TestMethod1()
{
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
async () =>
{
await ConnectToUSB.ConnectUSB();
}).AsTask().Wait();
}
}

Unit Tests Not Appearing

I'm using Visual Studio Express 2012 on the Windows 8 Release Preview and I can't seem to get my unit tests to appear in the test explorer.
I have a class called TestApp.Entity, and TestApp.EntityTest...
Here is my code:
namespace TestApp.Entity.Test
{
using System;
using System.Net.Http;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestApp.Domain;
[TestClass]
public class EntityTests
{
[TestMethod]
public async void TestObject1Deserialize()
{
Uri agencyUri = new Uri("*removed*");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(agencyUri);
string responseBodyAsText = await response.Content.ReadAsStringAsync();
List<Agency> agencyList = Deserializers.AgencyDeserialize(responseBodyAsText);
CollectionAssert.Contains(agencyList, new Agency() { Tag = "*removed*", Title = "*removed*", ShortTitle = "", RegionTitle = "*removed*" });
}
}
}
I assume that's all I needed to do, but they still don't appear in the test explorer. Any advice would be helpful.
As per Stephen Cleary, "you need to make your unit tests async Task instead of async void for them to work correctly".
This fixed the problem and the tests appeared. It's odd that no errors appeared when I used void, but now I know. Thank you!
I have Visual Studio 2012 and i couldn't see the Tests in Test Explorer,
So I installed the following: NUnit Test Adapter
That fixed the issue for me !
Do a rebuild all on the application, including any projects that contain test classes and test methods. They should appear in Test Explorer soon after.