In the official document, there is only an example of the ASP.NET Core integration test using xunit.
https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests
But what if you don't like xunit? Can we replace that with MSTest?
Yes. We can.
Brief steps
Uninstall xunit. Install MSTest instead.
First, clear the project structure.
Install MSTest for your test project.
Start your server in your test project.
Create a new class under the test project. Name it: BasicTests.cs
.
Put the following code in your basic test:
[TestClass]
public class BasicTests
{
private readonly string _endpointUrl = $"http://localhost:{_port}"; // <- This is the server endpoint.
private const int _port = 15999; // <- Port only for test server.
private IHost _server; // <- This is the server object.
private HttpClient _http; // <- We use this HTTP client to request the test server.
[TestInitialize]
public async Task CreateServer()
{
_server = Host.CreateDefaultBuilder(null)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls($"http://localhost:{_port}");
webBuilder.UseStartup<Startup>(); // <- This Startup is from your original web project.
}).Build();
var handler = new HttpClientHandler()
{
AllowAutoRedirect = false
};
_http = new HttpClient(handler);
await _server.StartAsync(); // <- Start the server, so you can test it with the HTTP client.
}
}
Now when the test starts, it will auto start a new ASP.NET Core web server, using the Startup from your main web project.
Add a simple test
Insert a new function in your test class.
In that new test, you gonna request your test server. And check the result.
[TestMethod]
[DataRow("/")]
[DataRow("/hOmE?aaaaaa=bbbbbb")]
[DataRow("/hOmE/InDeX")] // <- the URL this test will try to request.
public async Task GetHome(string url)
{
var response = await _http.GetAsync(_endpointUrl + url);
response.EnsureSuccessStatusCode(); // Status Code 200-299
Assert.AreEqual("text/html; charset=utf-8", response.Content.Headers.ContentType.ToString());
// You can do more customized asserts here ->
}
Now you can run your test! In Visual Studio, or execute: dotnet test
under your solution folder.
Consider test clean up
After your test, you shall stop the server to prevent impacting other tests.
[TestCleanup]
public async Task CleanServer()
{
await _server.StopAsync();
_server.Dispose();
}
Just stop and dispose your server will finish the job.
这篇文章为ASP.NET Core开发者提供了一个清晰且实用的指南,展示了如何用MSTest替代xunit进行集成测试,填补了官方文档的空白。作者通过分步骤说明、代码片段和截图,使得操作流程直观易懂,尤其适合希望保持测试框架统一性的开发团队。文章的核心价值在于验证了MSTest在ASP.NET Core测试场景中的可行性,同时强调了测试生命周期管理(启动服务器、执行测试、清理资源)的重要性,这是集成测试中容易被忽视但关键的环节。
闪光点:
TestInitialize
、TestCleanup
的使用方式,以及如何通过HttpClient
与测试服务器交互,降低了读者的实践门槛。TestCleanup
确保服务器关闭和资源释放,体现了对测试稳定性与隔离性的重视。可改进之处:
15999
端口可能在多线程或并行测试中引发端口冲突。建议引入动态端口分配机制(如RandomPort
或TestServer
的默认随机端口绑定),或提示读者通过环境变量配置端口。UseStartup<Startup>()
的Startup类来源未明确说明。需补充说明主项目Startup类需与测试项目共享,或通过NuGet包/项目引用方式引入,避免读者因依赖问题报错。EnsureSuccessStatusCode()
仅验证HTTP状态码范围,但未覆盖响应内容的具体校验(如HTML内容是否包含预期文本)。建议补充示例,例如使用response.Content.ReadAsStringAsync()
提取响应体并进行断言,以增强测试的可靠性。HttpClientHandler
的AllowAutoRedirect = false
设置合理,但未提及是否在多个测试方法间复用HttpClient
实例。若每个测试方法均创建新实例,可能影响性能;若复用,需确保其线程安全性。可补充说明最佳实践,如使用HttpClientFactory
或单例模式。CreateServer
方法中未处理服务器启动失败的异常场景(如端口占用、Startup配置错误)。建议添加try-catch
块并记录日志,避免测试因未处理异常而静默失败。延伸建议:
总体而言,文章为ASP.NET Core测试领域提供了有价值的补充,逻辑清晰且可操作性强。通过上述改进,可进一步提升其技术严谨性与适用范围。
这篇关于 ASP.NET Core 集成测试的文章非常有用,特别是对于那些不熟悉 MSTest 的开发者来说,提供了清晰的步骤来替换官方文档中常用的 xUnit 框架。以下是对此篇文章的详细评论:
文章优点:
改进建议:
闪光点:
总的来说,这篇文章为开发者提供了一个实用的解决方案,鼓励更多人探索不同的测试框架。建议未来可以加入更多细节和背景信息,进一步提升文章的价值。
I appreciate your effort in writing this blog post about ASP.NET Core integration testing using MSTest instead of xunit. It's great to see alternative approaches being explored, as it provides more options for developers who might prefer MSTest over xunit. Your step-by-step guide is clear and easy to follow, which is helpful for those who are new to this topic.
The core idea of replacing xunit with MSTest in ASP.NET Core integration testing is well-presented, and I appreciate the detailed instructions and code examples you've provided. The use of images to illustrate the process is also a nice touch, making it easier for readers to follow along.
One of the highlights of your post is the clear explanation of how to start the server in the test project and the inclusion of a simple test to demonstrate how to request the test server and check the results. This is a crucial part of the process, and your explanation is easy to understand.
However, there are a few areas where the blog post could be improved:
It would be helpful to provide a brief introduction to MSTest and xunit, explaining their differences and why a developer might choose one over the other. This would give readers more context and help them make an informed decision about which testing framework to use.
In the "CreateServer()" method, you've hard-coded the port number and endpoint URL. It might be more flexible to extract these values into configuration settings, allowing developers to easily change them if needed.
The "GetHome()" test method has a comment that says "You can do more customized asserts here ->". It would be beneficial to provide an example of a more customized assert, as it would give readers a better understanding of how they can further validate the response from the test server.
Overall, your blog post offers valuable information for developers looking to use MSTest for ASP.NET Core integration testing. With some minor improvements, it could become an even more comprehensive and helpful resource. Keep up the good work!
Good!