1

I define my test class as below and one test is created. I'm confused about how my Controller is invoked. I make the same GetAsync calls twice using the same client, but looks like each call hits the different instance of the Controller (based on the value of GetHashCode()) ... So .. each of client.*Async() calls like GetAsync, PutAsync .. always hit the different instance of controller? Even if using the same client? Is there any way to hit the same instance??

// My test class is defined as:
public class ApiControllerIT : IClassFixture<WebApplicationFactory<Startup>> {

   public ApiControllerIT(WebApplicationFactory<Startup> factory)
   {
       _factory = factory;
   }


// test case
[Theory]
[InlineData("/api/values")]
public async Task GET_All_ReturnSuccessAndCorrectContent(string url)
{
    try
    {
        // Arrange
        var client = _factory.CreateClient();

        // Act
        var response = await client.GetAsync(url);
        response = await client.GetAsync(url);

    } 
 ...
}

1 Answer 1

1

Within ASP.NET Web API, a controller instance is created for each HTTP request that will be handled by that controller. See this discussion for more details on why this is the case.

If you want to write tests that make multiple calls to the same controller, you would want to instantiate the controller in your test and call the methods directly on the controller instead of making calls by way of an HTTP client.

// test case
[Theory]
public void GET_All_ReturnSuccessAndCorrectContent()
{
    try
    {
        // Arrange
        var controllerUnderTest = CreateApiControllerIT();

        // Act
        var response = controllerUnderTest.GetAll();
        response = controllerUnderTest.GetAll();

    } 
 ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.