要进行 ASP.NET Core 集成测试,您需要遵循以下步骤:
Microsoft.AspNetCore.Mvc.Testing
包。安装命令:dotnet add package Microsoft.AspNetCore.Mvc.Testing
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace YourIntegrationTestsNamespace
{
public class IntegrationTests : IClassFixture>
{
private readonly HttpClient _client;
public IntegrationTests(WebApplicationFactory factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task Get_EndpointsReturnSuccessAndCorrectContentType()
{
// Arrange
// Act
var response = await _client.GetAsync("/your-controller/your-action");
// Assert
response.EnsureSuccessStatusCode(); // 确保请求成功
Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType.ToString());
}
}
}
在上述代码中,我们使用 WebApplicationFactory
类来创建一个测试服务器,并使用 HttpClient
来发送 HTTP 请求。
您可以使用 Visual Studio 的测试资源管理器或者运行以下命令来运行集成测试:
dotnet test
这样,您就可以进行 ASP.NET Core 集成测试了。请注意,以上示例仅提供了一个简单的示例,您可以根据您的具体需求进行更复杂的集成测试。