This is the continuation of our first article:
Preview
In this article, we will learn how to add a test project into our application and do automation tests for a class library project, which is created using .NET Core.
Step 1
Add Test Project to our solution
We will refer to the same solution to add our test project. Right click on Solution file and add new solution folder with the name “DotNetCoreTest”.
Step 2
Add new console application under “DotNetCoreTest” folder
Right click on “DotNetCoreTest” folder and add new project.
Select .NET Core from the left panel and click “Console Application (.NET Core)”. Give the name “TestLibrary” to our new project and click OK button.
A new project with the name “TestLibrary” will be added under the folder “DotNetCoreTest”.
Step 3
Add reference to Class library created using .Net Core
As explained in the previous article, we have created a class library with the name “DotNetCoreDemo” under the src folder.
We need to add the reference of that class library into our TestLibrary project.
Right click on “References” under the “TestLibrary” project and click “Add References..”
Select the DotNetCoreDemo from the list and click OK button. The reference of DotNetCoreDemo project should be added to the list.
Step 4
Add test packages using Nuget Package manager
Right click on References and select “Manage NuGet Packages.”
Choose "nuget.org" as the Package source, and click Browse tab. Check the Include prerelease checkbox and then browse for xUnit version 2.2.0 or newer. Subsequently, click Install.
Browse for one more package with name dotnet-test-xunit version 2.2.0 or newer and subsequently click Install.
Step 5
Add the code to test the .NET Core class Library
Before we start writing the code for testing, we need to edit our Project.json file.
Add "testRunner": "xunit", after the "frameworks" section.
Updated Project.json file will look as shown below.
Add new class file with the name “DotNetCoreTests.cs” under the “TestLibrary” Solution.
Add using Xunit and using DotNetCoreDemo to the top of the file and add the code, mentioned below to the class.
- [Fact]
- public void ValidateGetMessage()
- {
- Assert.Equal("Hello World!", new Class1().GetMessage());
- }
Step 6
Run the test
On the Test menu from Visual Studio, select Windows, Test Explorer and in Test Explorer, choose Run All.
The test will be passed without any error.
What we have learned so far.
- How to add a test project and refer existing class library created using .NET Core and add the test packages from NuGet Package Manager.
- Add the test code and run the project
References
For more details about xUNit, refer to the link.