Test for the software, is a key to ensure the quality of the process, the test is divided into a lot of kinds, unit testing, integration testing, system testing, pressure test and so on, different granularity for testing and test target is different also, such as unit testing, focus on every line of code, integration testing of multiple modules can normal work. When we measure code, one of the things we want to know is whether the code has been unit-tested, the quality of the testing, the code coverage? This paper will be introduced from the following aspects. Unit testing in Net Core:

  • Introduction to Unit Testing

  • Unit testing framework in.NET Core

  • Use xUnit.Net pairs. Net Core applications are unit tested

    • Create the xUnit.Net test project
    • Writing test methods
    • assertions
    • Running unit tests
  • Mock

  • Unit test code coverage

  • summary

Introduction to Unit Testing

Unit testing refers to the examination and verification of the smallest testable units in software, while. The smallest testable units in Net are classes and methods. Unit tests are white-box tests that focus on code execution logic, so unit test code is typically written by developers. Unit tests focus on two key unit is the smallest testable and code logic, but in many cases, a class or a method it will rely on some external components, such as other developers to write code, third-party libraries, database, network, etc., when the tested code with these components tightly coupled, then the code would be unpredictable, If a method relies on a database component to access the database, it must interact with the database while executing the method, and without the database, the method will not run. Therefore, unit test is not only to check the code logic, but also to limit the whole code structure. Object-oriented programming should follow the principle of “dependency inversion”, module should rely on abstraction, abstraction should not rely on implementation. And the dependent abstractions should be exposed by construction or method parameters so that the user of the component can see the dependency of the component at a glance. In order to shield these abstract dependencies during unit testing, stub, mock, fake and other methods are provided in different testing frameworks to simulate abstractions so that the code can be executed normally.

Unit testing framework in.NET Core

Common frameworks for unit testing in.NET Core are MSTest, NUnit, and xUnit.net. They are all used in a very similar way, declaring test methods with feature Assertions that are then used in the methods to determine whether they are performing as expected. Of the three frameworks MSTest is integrated with VS, while NUnit and xUnit.net are added. Net foundation, the following two figures, respectively is the comparison of the three frameworks and assertions features (content from: xunit. Making. IO/docs/compar… Features:

  

Assertion (part) :

   

The three frameworks have their advantages, but xUnit.net is more widely used (many open source projects use xUnit.net, including ASP.NET Core MVC, EF Core, etc.) and supported. Most of the platforms under Net (.NET Fx,.NET Core, UWP, Xamarin), and have very good scalability.

Use xUnit.Net pairs. Net Core applications are unit tested

This article uses the xUnit.Net framework. Net Core program unit test.

Create the xUnit.Net test project

Add in the solution. Net Core and xUnit tested items:

  

Directory structure:

  

The xUnit test project also provides a code profiler to help write test code:

  

Writing test methods

Add a calculator type to the project under test and add the addition method:

   

Add the test code for the Calulator method to the test project:

  

assertions

In programs, an assertion is an expression statement that is always True when executed. It helps code read, debug, compile, and defect detection. When the expression in the assertion is True, nothing is done, and when the result is false, exceptions are printed, as shown in the following figure. Assertions used by code provided in the System.Diagnositics namespace in.NET to debug code that breaks when x < y and throws an exception message:

  

More references: docs.microsoft.com/en-us/visua… In unit tests, the test method also uses assertions to verify that the program execution results match the expected results:

  

XUnit.net assertions reference: github.com/xunit/asser…

Running unit tests

You can run test methods in VS using the VS test window:

  

Running result (test passed) :

  

Run result (failed test) :

  

Mock

In the article mentioned earlier, object-oriented programming should show the dependence of the abstract, the influence of the unit test should be shielded rely on (both rely on is not achieved, or implement depends on the will hinder the code execution), in order to meet the demand in the Mock, Fake, and so on, the principle of which is to create a “Fake” rely on “empty”, Use it instead of a real dependency to make sure your code works. A common Mock framework in.NET is Moq. This article uses Moq to show you how to emulate dependencies: 1. Write dependent code:

  

  

The UserManager in the code above relies on a user’s repository type, which will interact with the database. 2. Install Moq components for the test project:

  

3. Write test code:

  

The above code mocks an IUserRepository type using the Moq component, sets its Add method and returns true, and creates the UserManager instance using the Mock Object instance. Finally assert that a FormatException is thrown if the age is negative when the user is created. 4. Run tests:

  

The test succeeded.

Unit test code coverage

Test code coverage is a measure of unit test, which can be used to measure whether the unit test reaches the standard. Generally, the code test goal is set at 80%-90%. In order to ensure code coverage, it is necessary to give full consideration to statement coverage, condition coverage, path coverage and other aspects when writing test cases. How does.NET Core calculate code coverage at test time? If using VS Enterprise, VS comes with code coverage analysis tools:

   

For more information: docs.microsoft.com/en-us/visua… Github.com/Microsoft/v… Note: VS is integrated with MSTest, so the code coverage analysis tool supports MSTest very well, but I haven’t tested how well xUnit.Net supports it.

For xUnit.net, code coverage can also be analyzed using the “OpenCover” and “ReportGenerator” tools. Here is how to analyze code coverage using these two tools: 1. Download and install OpenCover, download the latest release zip package from OpenCover GitHub, unzip it to the specified directory, and add the OpenCover directory to the environment variable:

  

Address: github.com/OpenCover/o…

2. Use the command line to complete coverage analysis with OpenCover: OpenCover has a number of parameters. For details, see github.com/OpenCover/o… In this case, you only need to specify that the target program is dotnet.exe and the target program parameter is test. Net Core CLI command dotnet test), in addition to specify the output file name, the register parameter is used to register code profiler default user can be used, the -filter parameter is used to filter the assembly and type do not need to analyze coverage, -oldstyle is used to support. Net Core program added parameters (see: github.com/OpenCover/o…) In addition, in order to meet the requirements of the test, the following nodes are added to the relevant project files (see: github.com/Microsoft/v…). :

<PropertyGroup>
    <DebugType>full</DebugType>
</PropertyGroup>
Copy the code

Finally, execute the following command in the project directory: OpenCover.Console.exe -target:”dotnet.exe” -targetargs:”test” -output:coverage.xml -register:user -filter:”+[*]* -[*Moq]* -[xunit*]*” -oldstyle

  

Generated results:

4. Use ReportGenerator to generate readable reports. Download address: github.com/danielpalme… Note: After the download is decompressed, add the directory ReprotGenerator to the environment variable for use. Exe “-reports:coverage. XML “”-targetdir:report”

  

Generated content:

  

Open the index.htm file:

  

5. Create a BAT file in the project to save code coverage detection and report generation commands for easy use:

  

summary

This article focuses on how to do this using the xUnit.net testing framework. Unit testing of Net Core applications, and the associated dependencies of simulating test targets through the Moq framework, avoids the influence of other components on the test code. At the end of the article, we introduced how to use the open source tools OpenCover and ReportGenerator to achieve this. Net Core unit test code coverage analysis, this solution is more difficult to use than VS Enterprise edition built-in tools, but fortunately, the tools are open source, continuous integration has good support, so it is a good solution. Unit testing can only ensure that the smallest executable units of software are correct. Real software is a whole composed of these smallest executable units. The correctness of units cannot guarantee the correctness of the whole. Net Core integration testing is introduced.

This paper links: www.cnblogs.com/selimsong/p…

Test code: github.com/yqszt/xUnit…

Reference: en.wikipedia.org/wiki/Unit_t… Docs.microsoft.com/en-us/dotne… Github.com/aspnet/Home… Asp.net – hacker. Rocks / 2017/03/31 /… Stackoverflow.com/questions/2… Blog. Ploeh. Dk/by /… Docs.microsoft.com/en-us/dotne… Stackoverflow.com/questions/3… Dotnetliberty.com/index.php/2… Github.com/moq/moq4 stackoverflow.com/questions/4… Github.com/OpenCover/o… Github.com/danielpalme…

Good code is tube out — talk about it. Net Core code management approach and implementation