首页 > 解决方案 > 集成单元测试未在 ASP.NET 核心 MVC/Web API 中运行

问题描述

我正在使用 ASP.Net 核心开发一个 Web API。我正在对我的项目进行集成测试。我正在关注此链接,https://koukia.ca/integration-testing-in-asp-net-core-2-0-51d14ede3968。这是我的代码。

我有控制器要在 thegoodyard.api 项目中进行测试。

namespace thegoodyard.api.Controllers
{
   [Produces("application/json")]
   [Route("api/category")]
   public class CategoryController: Controller
   {
      [HttpGet("details/{id}")]
      public string GetCategory(int id = 0)
      {
         return "This is the message: " + id.ToString();
      }
   }
}

我在解决方案中添加了一个名为 thegoodyard.tests 的新单元测试项目。我添加了一个具有以下定义的 TestServerFixture 类

namespace thegoodyard.tests
{
    public class TestServerFixture : IDisposable
    {
      private readonly TestServer _testServer;
      public HttpClient Client { get; }

      public TestServerFixture()
      {
         var builder = new WebHostBuilder()
                .UseContentRoot(GetContentRootPath())
                .UseEnvironment("Development")
                .UseStartup<Startup>();  // Uses Start up class from your API Host project to configure the test server

         _testServer = new TestServer(builder);
         Client = _testServer.CreateClient();
      }

      private string GetContentRootPath()
      {
         var testProjectPath = PlatformServices.Default.Application.ApplicationBasePath;
         var relativePathToHostProject = @"..\..\..\..\..\..\thegoodyard.api";
         return Path.Combine(testProjectPath, relativePathToHostProject);
      }

      public void Dispose()
      {
         Client.Dispose();
         _testServer.Dispose();
      }
   }
}

然后再次在测试项目中,我创建了一个名为 CategoryControllerTests 的新类,其定义如下。

namespace thegoodyard.tests
{
    public class CategoryControllerTests: IClassFixture<TestServerFixture>
   {
      private readonly TestServerFixture _fixture;

      public CategoryControllerTests(TestServerFixture fixture)
      {
         _fixture = fixture;
      }

      [Fact]
      public async Task GetCategoryDetai()
      {
         var response = await _fixture.Client.GetAsync("api/category/details/3");

         response.EnsureSuccessStatusCode();

         var responseString = await response.Content.ReadAsStringAsync();

         bool containMessage = false; //responseString.Contains("This is the message: 3"); - I commented on purpose to make the test fails.
         Assert.True(containMessage);
      }
   }
}

然后我在测试方法上右击并单击选项中的运行测试以运行测试。但是没有运行任何测试。这是输出。 在此处输入图像描述

我的代码中缺少什么?如何让我的集成测试运行?

标签: unit-testingasp.net-core.net-core

解决方案


请检查项目中的以下 NuGet 包:

Microsoft.AspNetCore.TestHost
Microsoft.NET.Test.Sdk
xunit
xunit.runner.visualstudio

推荐阅读