Search code examples
asp.net-core-webapiasp.net-core-2.1xunit.net

Debug Integration test and web api parallely in single .net core 2.2 in single application?


I have created web Api in .net core 2.2 in visual studio 2017. In the same project I also add new project of unit testing to test the created web api. Now when I debug unit test, it is not working and I can not debug the unit test in debug mode of web api. Please help me to find out the solution of above problem.

Created Api to get the list of users from database with search feature. Create XUnit test project in same solution to test the created Api. When I try to run XUnit test project, it is showing internal server error and the test is not debuging when I run the web Api. Below is the Sample code. There are 2 Project files in single solution. One is for Api and another is for Testing.

[HttpPost]
        public ActionResult SearchCustomer(CustomerSearch objsearch)
        {
            var Search=_ourCustomerRespository.SearchCustomer(objsearch);

            if (Search.Count() == 0)
            return StatusCode(204,new {message = "No Record Found!"});

            return Ok(Search);
        }




[Fact]
        public async Task SearchCustomers()
        {

            var response = await _TestFixture.Client.PostAsync("api/Customer/SearchCustomer", new StringContent(
            JsonConvert.SerializeObject(new CustomerSearch
            {
                custid = 2,
                custfname = "",
                custlname = "",
                custemail = "",
                custorderby = "customerid",
                custsortdirection = "asc",
                custpagesize = 10,
                custpagenumber = 0
            }), Encoding.UTF8, "application/json"));
            response.StatusCode.Should().Be(HttpStatusCode.OK);
        }

Solution

  • Well, your problem in a nutshell is that you're not unit testing. The API is an external dependency, and unit tests, by definition, do not have external dependencies. Dependencies like this need to be mocked, exactly because of the issue you're now experiencing: your test can fail because there's a problem with the dependency and not the actual code being tested.

    If you want to test the full interaction between code and a live API, that is considered an integration test, and in such a situation, you'd have way of ensuring that the external dependency is satisfied outside of the test itself. For example, you might hit a specifically deployed "test" environment API.