综合测试 - ASP.NET 核心

Integ Tests - ASP.NET Core

我如下定义我的测试 class 并创建一个测试。我对如何调用我的控制器感到困惑。我使用相同的客户端两次调用相同的 GetAsync 调用,但看起来每次调用都会命中控制器的不同实例(基于 GetHashCode() 的值)...所以..每个 client.*Async() 调用都像GetAsync、PutAsync .. 总是命中控制器的不同实例?即使使用相同的客户端?有什么办法可以打同一个实例吗??

// 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);

    } 
 ...
}

在 ASP.NET Web API 中,为每个将由该控制器处理的 HTTP 请求创建一个控制器实例。请参阅 this discussion 以了解有关为什么会出现这种情况的更多详细信息。

如果您想编写对同一控制器进行多次调用的测试,您可能希望在测试中实例化控制器并直接在控制器上调用方法,而不是通过 HTTP 客户端进行调用。

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

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

    } 
 ...
}