【发布时间】:2019-02-20 17:47:23
【问题描述】:
我正在使用 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);
}
}
}
然后我在测试方法上右击并单击选项中的运行测试以运行测试。但是没有运行任何测试。这是输出。
我的代码中缺少什么?如何让我的集成测试运行?
【问题讨论】:
-
您的 csproj 文件中是否有 Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" 用于测试项目?尝试删除它。如果没有帮助,请检查此stackoverflow.com/questions/35103781/… 以确保尚未解决问题。
标签: unit-testing asp.net-core .net-core