Unit Tests Not Appearing - unit-testing

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.

Related

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.

Unit Testing in Nancy causing Routebuilder exception using TinyIoc

Getting a System.MissingMethodException, Method not found: 'Void RouteBuilder.set_Item()
Get["/foo"] = parameters => { return Bar(Request);};
This runs fine when calling from browser, but fails when testing with this setup
var browser = new Browser(with =>
{
with.Module<Foobar>();
}
var response = brower.Get("/Foo", with => {with.HttpRequest();});
Any clue why the Routebuilder for testing won't pick up this route?
Turns out I had created the test project using the pre-release version of Nancy.Testing. This in turn made TinyIOC unhappy when trying to build routes/dependencies. So, if you see this mysterious message, check that your working code and test code are referencing the same packages.

Can't overload async/await methods with NUnit Test Adapter

I'm getting a System.Reflection.AmbiguousMatchException when at least one of the methods are async and the method names match when the NUnit tests are run using the NUnit Test Adapter 2.0.0.0 in Visual Studio. I'm able to run the tests without problem when I use the ReSharper unit test runner and when I use the NUnit GUI test runner (NUnit-2.6.4.msi). Is this a bug in the NUnit Test Adapter?
[TestFixture]
public class SimpleRepro
{
[Test]
[TestCase("I'm valid")]
[TestCase("So am I!")]
public async Task Foo(string resource)
{
Assert.IsNotNull(resource);
await Task.Delay(new TimeSpan(0, 0, 1));
}
[Test]
public async Task Foo()
{
Assert.IsNotNull(Guid.NewGuid().ToString("N"));
await Task.Delay(new TimeSpan(0, 0, 1));
}
}
I've cross posted this on the GitHub issues list.
This was confirmed as a bug by one of the library owners. According to their comment it looks like this will be addressed in a future release:
Since it only occurs in the adapter, it should be something we can fix!
This is great news of course. In the mean time you can work around this issue by not overloading async/await methods in your unit tests.

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();
}
}