【发布时间】:2020-04-08 06:13:07
【问题描述】:
我创建了一个简单的项目来进行单元测试,这里是示例代码:
[TestMethod]
public async Task GetCountry_ShouldReturnAndorra()
{
// Arrange
int countryId = 1;
string requestUrl = baseUrl + "/Countries/" + countryId;
// Act
// GET : /api/v1/Locations/Countries/{countryId}
HttpResponseMessage response = await client.GetAsync(requestUrl);
// Assert
Assert.IsTrue(response.IsSuccessStatusCode, "Response StatusCode is not success");
string value = await response.Content.ReadAsStringAsync();
Assert.IsNotNull(value);
var country = DeserializeCountryResponse(value);
Assert.AreEqual(country.data.Id, countryId);
Assert.AreEqual(country.errors.Count, 0, 0, "Reponse contains errors");
}
而这个项目取决于API服务器是否运行以及它的依赖(数据库等)
但是文档说这不是最佳实践 (https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices#characteristics-of-a-good-unit-test):
良好单元测试的特征
...
独立。单元测试是独立的,可以独立运行,并且不依赖于任何外部因素,例如文件系统或数据库。
...
那么你应该走这条路还是有另一条路?
【问题讨论】:
标签: c# unit-testing asp.net-web-api