. NET Core Series: 4 testing

Source: Internet
Author: User
Tags dotnet xunit

Microsoft has officially released the. NET Core 1.0 RTM in 2016.6.27, but the toolchain is still in preview, and the same number of open source test libraries have at least released Alpha Beta support for. NET core, this article the state of. NET Core Testin G Today summarizes the current progress of each open source test library. The purpose of this article is to be able to test when we build our application, and how to use Xunit together you can do unit testing by adding different test cases nsubstitute to your project while integrating tests across the entire project. This time we are writing using visual Studio Update 3. Xunit.net is an open source testing tool based on the. NET Framework. The xunit.net can be used for C#/F#/VB. NET, etc. for unit testing. The ASP. NET Core is more straightforward to say goodbye to the previous visual Studio Unit Test Framework, while the direct use of the xunit.net,xunit.net is based on NUnit. From the website or the official web site, you can find many advantages of xunit, compared with NUnit and other test frameworks have some advantages
1) Generate an object instance for each test method
2) canceled [SetUp] and [TearDown]
3) canceled [ExpectedException]
4) features similar to aspect
5) Reduced number of custom attributes (Attribute)
6) Adopt generic type
7) Anonymous delegation
8) Extensible Assertion
9) Scalable test methods
10) Extensible Test class

Learn more about Xunit.net here (click to open the link [discard NUnit hug xunit]).

Using the Xunit.net Unit test

First we are similar to the. NET Core Series: 3, creating a solution with multiple projects Testdemo, adding a class library project called Dotnetcorelib,library.cs is also replaced by:

Namespace Dotnetcorelib
{
public class Calculator
{
public int Multi (int x, int y)
{
return x * y;
}
}

}

Below we are going to create a test project for Dotnetcorelib, and we will create the process by referring to the article https://github.com/dotnet/core-docs/tree/master/samples/core/ Getting-started/unit-testing-using-dotnet-test, we modify the Project.json of the Dotnetcorelibtest project, add xunit related NuGet package references, and modify the partial configuration.

Also we set the framework node to netcoreapp1.0, dependent on the Xunit and Xunit.runner packages

"Dependencies": {
"Dotnet-test-xunit": "2.2.0-preview2-build1029",
"Dotnetcorelib": {
"Version": "1.0.0-*",
"Target": "Project"
},
"Xunit": "2.2.0-beta2-build3300",
"Xunit.runner.console": "2.2.0-beta2-build3300"
}

Calculator then began testing our class library calculator, modifying Class1.cs to CalculatorTest.cs,

Using Dotnetcorelib;
Using Xunit;

Namespace Dotnetcorelibtest
{
public class Caltest
{
Private ReadOnly Calculator Calculator;


Public Caltest ()
{
Calculator = new Calculator ();
}

[Fact]
public void Onemutioneisone ()
{
var result = Calculator. Multi (1, 1);
Assert.equal (1, result);
}

[Theory]
[Inlinedata (-1)]
[Inlinedata (0)]
[Inlinedata (1)]
public void returnvalue (int value)
{
var result = Calculator. Multi (1,value);

Assert.equal (result, value);
}
}
}

Of the two tests above, we used 2 features [fact] and [theory], the [fact] property represented as a single test for a method, and the [Theory] property represents a test suite that executes the same code but has different input parameters. The [Inlinedata] property can be used to specify values for these inputs. By using the attributes [Fact] and [Theory],xunit], we understand that this is a test method and then run the method. In a test method, we typically follow a three-step AAA pattern:

    1. Arrange: Preparing for the test
    2. Act: run SUT (the code for the actual test)
    3. Assert: Verify Results

Below we run dotnet test to see the results.

C:\Users\geffz\Documents\Visual Studio 2015\projects\testdemo\dotnetcorelibtest>dotnet Test
Project Dotnetcorelib (. netcoreapp,version=v1.0) was previously compiled. Skipping compilation.
Project dotnetcorelibtest (. netcoreapp,version=v1.0) was previously compiled. Skipping compilation.
Xunit.net. NET CLI Test Runner (64-bit. NET Core win10-x64)
Discovering:dotnetcorelibtest
Discovered:dotnetcorelibtest
Starting:dotnetcorelibtest
Finished:dotnetcorelibtest
= = = TEST execution SUMMARY = = =
Dotnetcorelibtest Total:4, errors:0, failed:0, skipped:0, time:0.206s
Summary:total:1 targets, Passed:1, failed:0.

The above output we know that 4 tests have been performed, all passed, the [face] attribute identifies the test case that represents a fixed input, and the [theory] attribute identifies a test case that can specify multiple inputs, combined with the Inlinedata attribute identification. In the above example, a total of three inlinedata feature identifiers are used, each setting has a different value, and when the unit test is executed, the set value is assigned by the test framework to the parameters of the corresponding test method. You can allow your code to be fully tested by adding different test cases to your project.

Xunit.net paired with Nsubstitute for unit testing

In a well-structured project, each layer relies on a pre-agreed interface. In multi-person collaborative development, most people will only be responsible for their own part of the module function, development progress is often inconsistent. While other modules that a developer relies on to unit-test their modules have not yet been developed, it is necessary to provide impersonation capabilities to the dependent interfaces by mocking them to complete the unit testing of their modules without actually relying on the specific functionality of the other modules. At this point we usually need to have a unit test simulation class library, the developer has been to the mocking class library syntax of the simplicity of a strong demand, nsubstitute try to meet this demand. The simple and straightforward syntax allows us to focus on the test itself rather than on the creation and configuration of the test substitution instance. Nsubstitute has tried to make the most common operational requirements simple, easy to use, and to support some of the less common or exploratory features, while also minimizing its syntax to natural language. For more detailed information about Nsubstitute, go to the Nsubstitute Full manual index.

Nsubstitute has released the 2.0 RC version to support. NET Core. Introducing Nsubstitute related NuGet packages:

We extracted the interface ICalculator under the Calculator class refactoring:

public interface ICalculator
{
int Multi (int x, int y);
}

We can let Nsubstitute create an alternative instance of the type instance, create a Stub, Mock, Fake, Spy, Test Double, and so on, but why bother us when we just want a substitute instance with some degree of control? We can tell the created alternate instance to return a value when the method is invoked:

[Fact]
public void Test_getstarted_returnspecifiedvalue ()
{
ICalculator calculator = substitute.for<icalculator> ();
Calculator. Multi (1, 2). Returns (2);

int actual = Calculator. Multi (1, 2);
Assert.equal (2, Actual);
}

Below we run dotnet test to see the results, add the above 2 use cases, more detailed information about Nsubstitute please go to the Nsubstitute Full manual index.

Integration Testing

Above, we just unit-tested the logic. For an ASP. NET Core project, you also need to simulate testing each request portal in the context of site deployment. NET Core provides great support for quick and easy integration testing.

The TestServer class performs most of the heavy lifting of the integration test in ASP. Microsoft.AspNetCore.TestHost package has this class. This section is from the MSDN Magazine ASP. NET core-the actual ASP. Web Core MVC filter, which does not require a database or an Internet connection or a server that is running. They are as fast and simple as unit tests, but most importantly, they allow you to test an ASP. NET application in the entire request pipeline, not just an orphaned method in the Controller class. It is recommended that you write unit tests as much as possible and return to integration tests for behaviors that fail unit testing, but it is great to run integration tests in ASP. NET Core using such a high-performance approach.

By simultaneously simulating the communication between the service side (TestServer) and the client (HttpClient) in a project, the purpose of the overall test Webapi interface is achieved, and the relevant code is placed in the https://github.com/ardalis/ Gettingstartedwithfilters/tree/master/integrationtests. The article tests the filters for ASP. NET core MVC, because it is difficult to test such scenarios by writing unit tests, but it is possible to achieve the same goal through the integration testing of ASP.

Using System.IO;
Using System.Net.Http;
Using System.Net.Http.Headers;
Using Filters101;
Using Microsoft.AspNetCore.Hosting;
Using Microsoft.AspNetCore.TestHost;

Namespace integrationtests
{
    public class Authorscontrollertestbase
     {
        protected HttpClient getclient ()
         {
            var builder = new Webhostbuilder ()
                . Usecontentroot (Directory.GetCurrentDirectory ())
                . Usestartup<startup> ()
                . Useenvironment ("testing");
            var server = new TestServer (builder);
            var client = server. CreateClient ();

Client always expects JSON results
Client. Defaultrequestheaders.clear ();
Client. DEFAULTREQUESTHEADERS.ACCEPT.ADD (
New Mediatypewithqualityheadervalue ("Application/json"));

return client;
}
}
}

Using System.Collections.Generic;
Using System.Linq;
Using System.Net.Http;
Using System.Threading.Tasks;
Using Filters101.models;
Using Newtonsoft.json;
Using Xunit;

Namespace Integrationtests.authorscontroller
{
public class Get:authorscontrollertestbase
{
Private ReadOnly HttpClient _client;

Public Get ()
{
_client = base. Getclient ();
}

        [theory]
        [inlinedata ("authors")]
        [Inlinedata ("authors2")]
         Public Async Task returnslistofauthors (string controllername)
        {
            var response = await _client. Getasync ($ "/api/{controllername}");
            Response. Ensuresuccessstatuscode ();
            var stringresponse = await response. Content.readasstringasync ();
            var result = Jsonconvert.deserializeobject <IEnumerable<Author>> (Stringresponse). ToList ();

Assert.equal (2, result. Count ());
Assert.equal (1, result. Count (A = A.fullname = = "Steve Smith");
Assert.equal (1, result. Count (A = A.fullname = = "Neil gaiman"));
}
}
}

The client in this case is the standard System.Net.Http.HttpClient that you can use to make a request to the server, just as you would with a network. But because all requests are in memory, testing is extremely fast and reliable. Perform unit tests in the CMD window to view test results

. NET Core Series: 4 testing

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.