Good code is in the pipeline. Unit testing and code coverage in ——. Net core

Source: Internet
Author: User
Tags dotnet xunit

Testing for software, is to ensure the quality of an important process, and testing is divided into many kinds, unit testing, integration testing, system testing, stress testing, and so on, different test granularity and test objectives are different, such as unit testing focus on each line of code, integration testing is concerned about whether multiple modules can work together properly.
When we measure the quality of the code, one of them is whether the code is unit-tested, how much is the test, the code coverage? This article describes the unit tests in. Net core in the following ways:

    • Introduction to Unit Testing
    • Unit test framework in. Net Core
    • Unit test for. Net Core applications using Xunit.net
      • To create a xunit.net test project
      • Writing test methods
      • Assertion
      • Run unit Tests
    • Mock
    • Unit Test Code Coverage
    • Summary
Introduction to Unit Testing

Unit testing refers to the inspection and validation of the smallest testable unit in the software, while the smallest testable unit in. NET is the class and method, and the unit test is a white-box test that focuses on the code execution logic, so the unit test code is generally written by the developer.
The two focuses of unit testing are the smallest testable unit and code logic, but in many cases a class or method relies on external components, such as code written by other developers, third-party class libraries, databases, networks, and so on, when the code being tested is tightly coupled with these components, the code will probably be unpredictable. , such as a method that relies on a database component to access the database, then in the execution of this method, it is necessary to interact with the database, if there is no database, then the method will not run.
So unit testing is not only to check the code logic, but also to the entire code structure is limited, object-oriented programming should follow the "dependency inversion" principle, the module should rely on abstraction, the abstraction should not rely on the implementation . and depending on the abstraction, it should be shown by the construction or method parameters exposed , so that the user of the component's dependency on the component at a glance.
In the case of unit testing, in order to shield these abstract dependencies, the different test frameworks provide stubs, mocks, fake, and so on to simulate the abstraction so that the code can execute normally.

Unit test framework in. Net Core

The framework for unit tests commonly used in. Net core is MSTest, NUnit, and xunit.net, and they are used in very similar ways, by declaring test methods in the form of attribute tags, and then using assertions in methods (assertions) To determine whether the results of the execution of the method are up to expectations.
MSTest in these three frameworks are integrated with VS, while NUnit and Xunit.net have joined the. NET Foundation, the following two graphs are three framework features and assertions compared (content from: https://xunit.github.io/docs/comparisons):
Characteristics:

  

Assertion (partial):

   

The three frameworks have their advantages, but xunit.net is more widely used (many open source projects use xunit.net, including projects such as ASP. NET Core MVC, EF core, etc.), supported. NET, most platforms (. NET Fx,. NET Core, UWP, Xamarin), and have very good extensibility.

Unit test for. Net Core applications using Xunit.net

This article uses the Xunit.net framework to perform unit testing on. Net core programs.

To create a xunit.net test project

Add the tested project for. Net Core and the Xunit test project in the solution:

  

Directory structure:

  

The Xunit test project also provides the appropriate code parser to help write the test code:

  

Writing test methods

Add a calculator type to the project you are testing and add a method for adding operations:

To add the test code for the Calulator method in the test project:

  

Assertion

In a program, an assertion is always true when an expression statement is executed (true), which facilitates code reading, debugging, compiling, and flaw detection, and when an assertion is executed as True, no action is taken, and when the result is false, some exception information is output. The assertion usage for code debugging that is provided under System.diagnositics namespaces in net (when the debugger is debugged, the parameters x < Y are interrupted and the exception information is thrown):

  

More information: Https://docs.microsoft.com/en-us/visualstudio/debugger/assertions-in-managed-code
In unit tests, the test method also uses assertions to determine whether the program execution results match the expected results:

  

Assertions in Xunit.net reference: Https://github.com/xunit/assert.xunit

Run unit Tests

You can use the VS Test window to run the test method in VS:

  

Run results (test pass):

  

Run results (test failed):

  

Mock

As mentioned earlier in the article, object-oriented programming should show the dependency abstraction, the unit test should be the impact of shielding dependencies (whether the dependency has not been implemented, or the implementation of the dependency will hinder code execution), in order to meet this demand, there is a mock, fake, etc., the principle is to create a "false" "empty" dependency , and use it instead of a real dependency to ensure that the code is able to run.
. NET a common mock frame is MOQ, this article will use MOQ to describe how to simulate dependencies:
1. Write the code that you want to rely on:

  

  

In the code above, Usermanager relies on a user's warehousing type, which will interact with the database.
2. Install the MOQ component for the test project:

  

3. Write the Test code:

  

The above code mocks a iuserrepository type through the MOQ component and sets its Add method and returns True ( Note: The data of the parameter when the method is set is the same as when the call was used ). Finally, the Usermanager instance is created from the object instance of the mock.
The last assertion is that when the user is created, a negative age throws formatexception.
4. Run the test:

  

The test was successful.

Unit Test Code Coverage

Test code coverage is a measure of unit testing, can be used to measure whether the unit test is standard, usually set the code test target between 80%-90%, in order to ensure code coverage, in writing test cases from the statement coverage, conditional coverage, path coverage and so on to fully consider.
And how does the. Net core calculate code coverage when testing? If you use Vs's Enterprise Edition, then vs comes with the Code Coverage Analysis tool:

   

Detailed reference: https://docs.microsoft.com/en-us/visualstudio/test/using-code-coverage-to-determine-how-much-code-is-being-tested
Https://github.com/Microsoft/vstest-docs/blob/master/docs/analyze.md#coverage
  Note: vs integrates mstest, so the Code Coverage Analysis tool is very good for mstest support, but the support for xunit.net is not tested by the author.

For xunit.net, the analysis of test code coverage can also be done through the "Opencover" and "Reportgenerator" tools, which show you how to perform code coverage analysis with these two tools:
1. Download and install Opencover, load the latest release Zip package on Opencover GitHub, unzip to the specified directory, and add the Opencover directory to the environment variable:

  

Address: https://github.com/OpenCover/opencover/releases

2. Use Opencover with the command line to complete the coverage analysis:
Opencover has many parameters, specific reference: Https://github.com/OpenCover/opencover/wiki/Usage
In this case, you only need to specify that the target program is Dotnet.exe, the target program parameter is test (note:. NET core's test functionality is actually done with the. NET Core CLI command dotnet test), and the output file name is specified. The register parameter is used for registering Code Analyzer by default with user, and the-filter parameter is used to filter assemblies and types that do not require analysis coverage,-oldstyle is to support the parameters added by the. Net Core program (see: Https://github.com /opencover/opencover/issues/595)
In addition, in order to be able to meet the test need to add the following node in the relevant project file (see: https://github.com/Microsoft/vstest/issues/800):

< PropertyGroup >    < Debugtype >full</debugtype></propertygroup  >

Finally, execute the following command under the project directory:
Opencover.console.exe-target: "Dotnet.exe"-targetargs: "Test"-output:coverage.xml-register:user-filter: "+[*]*-[* moq]*-[xunit*]* "-oldstyle

  

Result of the build:

4. Generate a readable report from Reportgenerator:
: https://github.com/danielpalme/ReportGenerator/releases
  Note: After downloading the extract, add the Reprotgenerator directory to the environment variable for use.
Execute the following command:
ReportGenerator.exe "-reports:coverage.xml" "-targetdir:report"

  

Generate content:

  

Open index.htm File:

  

5. Create a BAT file in your project that holds code coverage detection and report generation commands for ease of use:

  

Summary

This article mainly describes how to use the Xunit.net test framework to complete unit testing of. Net core programs, and to simulate the dependencies of test targets through the MOQ framework, avoiding the impact of other components on the test code.
The article concludes with an introduction to how to use the open source Tools Opencover and Reportgenerator tools to implement. Net Core Unit test Code Coverage analysis, which is a bit more cumbersome than vs. Enterprise's own tools, but fortunately the tools are open source, There is also better support for continuous integration, so it is a good solution.
Unit testing only guarantees that the smallest executable unit of the software is correct, the real software is a whole of these smallest executable units, the correctness of the unit is not guaranteed overall correctness, the next article will be introduced to. Net Core integration testing.

This article link: https://www.cnblogs.com/selimsong/p/9263957.html

Test code: Https://github.com/yqszt/xUnitTestDemo

Reference:
https://en.wikipedia.org/wiki/Unit_testing
https://docs.microsoft.com/en-us/dotnet/core/testing/
Https://github.com/aspnet/Home/wiki/Engineering-guidelines#unit-tests-and-functional-tests
HTTP// asp.net-hacker.rocks/2017/03/31/unit-testing-with-dotnetcore.html
https://stackoverflow.com/questions/ 261139/nunit-vs-mbunit-vs-mstest-vs-xunit-net
http://blog.ploeh.dk/2010/04/26/ whyimmigratingfrommstesttoxunit.net/
Https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-test?tabs= NETCORE21
https://stackoverflow.com/questions/38425936/ How-to-measure-code-coverage-in-asp-net-core-projects-in-visual-studio
http://dotnetliberty.com/index.php/ 2016/02/22/moq-on-net-core/
Https://github.com/moq/moq4
https://stackoverflow.com/questions/41384459/ Opencover-reports-missing-pdbs-when-pdbs-are-present-xunit-net-core
Https://github.com/OpenCover/opencover
Https://github.com/danielpalme/ReportGenerator

Good code is out of the box--talking about the code management method of. Net core and landing (update ... )

Good code is in the pipeline. Unit testing and code coverage in ——. Net core

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.