Integration testing of ASP. NET Core Webapi using Xunit

Source: Internet
Author: User

Tags: SPI picture name RECT server Framework running IMG Control

New projects we use the front-end separation, the backend with the ASP. NET core Webapi, how to test the backend code automatically, there are several scenarios:

1. Unit testing, the current program for us is very difficult, put aside the time of the problem, unit testing on the level of development personnel requirements are very high, leave aside.

2. Use third-party tools such as postman to test the WEBAPI with simulated HTTP requests. The disadvantage is that WEBAPI must run, not like unit tests, click a button to run the test.

3. Using unit test tools such as Xunit to test the WEBAPI, in order to solve the postmam problem, we use Xunit to perform class unit tests on Webapi.

The main ideas for testing WEBAPI using unit test tools such as Xunit are:

1. Start the WEBAPI project with code, just like the code in Program.cs

2. Using the HTTP Tool class library to send HTTP requests to WEBAPI, here we use RESTSHARP, see official website: http://restsharp.org/.

3. Receive the return value, make an assertion judgment, we use the shouldly framework.

Here is the specific code:

First create the test project, this is the Visual Studio 2017 comes with the Xunit test project, you can see the sincerity of Ms.

Then we create a class that starts Webapi:

 Public classapiserverrunning:idisposable {PrivateIwebhost _builder;  Public voidDispose () {_builder?.        Dispose (); }         Public voidGivenrunningon (stringURL) {_builder=NewWebhostbuilder (). Useurls (URL). Usekestrel (). Usecontentroot (Directory.GetCurrentDirectory ()). Usestartup<Startup>()                   .            Build (); _builder.        Start (); }    }

Then we come across a problem, when to start Webapi, not every unit test to start once, not run each class is started once, but the entire test project runs only one, here is the use of Xunit icollectionfixture,

If you want to know the details, please Baidu yourself. Here is the code directly:

/// <summary>    ///used to startup Weiapi, run only once/// </summary>     Public classtestfixture:idisposable { PublicApiserverrunning _server =Newapiserverrunning ();  Publictestfixture () { This. Given (s = =_server. Givenrunningon (Testconst.server_url)). Then (x=X.connect ()).        Bddfy (); }        Private voidConnect () {Console.WriteLine ("WEBAPI startup successfully!!!"); }         Public voidDispose () {}}
    /// <summary>    /// used to tag every class using Test fixture     /// </summary>    [Collectiondefinition ("testcollection")]      Public class Testcollection:icollectionfixture<testfixture>    {    }

With the above two classes, we can then write unit tests:

[Collection ("testcollection")]     Public classtaskcontrollertest:testbase {[Fact (DisplayName="Get list")]        Private voidgetopiniontaskhospitals_test () {varReq = Agent. Createrequest ("Gettasks")                . Addparameter ("Month","2015-07-01")                .            AddHeader (Fmconsts.headername_userinfo, testconst.user_info); varrel = Agent. Execute<<list<task>>>(req); Rel. Result.Count.ShouldNotBe (0); }    }

Each class sends a request, so here's a testbase base class with an HTTP object for the agent, and we're enclosing the Restsharp HTTP request object, which is not posted here.

And if not logged in, all if you want to use the login cookie, here I was directly added a header information, equivalent to a login, but there must be problems may expire, of course, more than the difficulty.

There is also a difficult point, is the test here, or the use of our development database, this test will contaminate the data, due to the development of data variables, will also affect the test results, if the replacement of the development database Oracle memory data for the library, and the code changes are very small, is our next work. Please advise the students with experience.

Integration testing of ASP. NET Core Webapi using Xunit

Related Article

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.

Tags Index: