Once you have your UWP application ready for tests you should add test application to your solution. To do it "right" click on the solution and choose "Unit Test App (Universal Windows)":
Once you add it to the solution there are few more steps required to configure it. You will be asked for selecting target and minimum platform version:
Once you select them, open "project.json" file and add below dependencies:
"dependencies":
{
"Microsoft.NETCore.UniversalWindowsPlatform": "5.1.0",
"xunit.runner.visualstudio": "2.1.0",
"xunit": "2.1.0",
"xunit.runner.devices": "2.1.0"
}
These are used to download and add NuGet xUnit Framework packages to make unit tests easy for UWP application.
Remove reference called “MSTestFramework.Universal”:
Now open “UnitTest.cs” file. Modify it to look like below:
using System;
using Xunit;
namespace UnitTestsForUwp
{
public class UnitTest1
{
[Fact]
public void TestMethod1()
{
Assert.Equal(4, 4);
}
[Theory]
[InlineData(6)]
public void TestMethod2(int value)
{
Assert.True(IsOdd(value));
}
bool IsOdd(int value)
{
return value % 2 == 1;
}
}
}
}
It is good to stop here for a moment to talk a little bit about xUnit attributes:
a. Fact- tests which are always true. They test invariant conditions.
b. Theory – tests which are only true for a particular set of data.
Now we would like to prepare the app to display information about tests but not only - it is good to have one good way to start tests. To achieve that we need to make small changes in "UnitTestApp.xaml" file. Open it and replace all code with pasted below:
<ui:RunnerApplication
x:Class="UnitTestsForUwp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UnitTestsForUwp"
xmlns:ui = "using:Xunit.Runners.UI"
RequestedTheme="Light">
</ui:RunnerApplication>
Remember that "local" should have the same name like your namespace.
Now open "UnitTestApp.xaml.cs" and replace code with below:
sealed partial class App : RunnerApplication
{
protected override void OnInitializeRunner()
{
AddTestAssembly(GetType().GetTypeInfo().Assembly);
InitializeRunner();
}
partial void InitializeRunner();
}
That's it! Now rebuild project and launch test application. As you can see below you have access to all your tests, you can start them and check results: