unit-testing - 集成单元测试未在 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);
}
}
}
然后我在测试方法上右击并单击选项中的运行测试以运行测试。但是没有运行任何测试。这是输出。
我的代码中缺少什么?如何让我的集成测试运行?
解决方案
请检查项目中的以下 NuGet 包:
Microsoft.AspNetCore.TestHost
Microsoft.NET.Test.Sdk
xunit
xunit.runner.visualstudio
推荐阅读
- sql - Find value contained in the HierarchyId at any level
- c# - OpenXML reference document parts multiple time
- java - Finding random (auto) id assigned to our document by Firestore
- sql - Adding data to existing table with primary key violates unique constraint despite being unique?
- youtube-api - youtube search change the pages token
- javascript - How i can make invite logger with Discord.js?
- node.js - How can increment a new field in mongoose rather than update entire document?
- git - Undo changes in code (whole project) to a specific commit but Keep all the "git logs" (using git bash)
- python-3.x - 通过 python 获取所有可用函数的列表,本地的、全局的还是导入的?
- javascript - 创建“快捷方式”来操作深度嵌套的对象键