Integration testing of ASP. NET Core Webapi using Xunit

Source: Internet
Author: User
Tags xunit

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 class ApiServerRunning : IDisposable
    {
        private IWebHost _builder;

        public void Dispose()
        {
            _builder?.Dispose();
        }

        public void GivenRunningOn(string url)
        {
            _builder = new WebHostBuilder()
                   .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 class TestFixture : IDisposable
    {
        public ApiServerRunning _server = new ApiServerRunning();

        public TestFixture()
        {
            this.Given(s => _server.GivenRunningOn(TestConst.SERVER_URL))
                .Then(x => x.Connect())
                .BDDfy();

        }
        private void Connect()
        {
            Console.WriteLine("webapi startup successfully!!! ");
        }

        public void Dispose()
        {
        }
    }
    /// <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 class TaskControllerTest : TestBase
     {
         [Fact(DisplayName = "Get List")]
         Private void GetOpinionTaskHospitals_Test()
         {
             Var req = agent.CreateRequest("GetTasks")
                 .AddParameter("month", "2015-07-01")
                 .AddHeader(FmConsts.HeaderName_UserInfo, TestConst.USER_INFO);

             Var rel = 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.

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.