c# - Web API 单元测试未按预期工作

标签 c# unit-testing asp.net-web-api

我是 Web API 的新手。我继承了用 c# 编写的单元测试代码。但是,当我运行单元测试时,无论 Controller 名称如何,测试都会通过。例如:http://localhost/api/users -> 即使用户拼写错误,单元测试也会通过。

我在 Controller 中有以下代码:

public async Task TestGetUsers()
{
    usersController controller = new usersController(new TestUserRepository());
    ApiControllerConfig.SetupControllerForTest(controller, "http://localhost/api/users", HttpMethod.Get);
    IHttpActionResult result = controller.Get();
    HttpResponseMessage message = await result.ExecuteAsync(CancellationToken.None);
    string content = await message.Content.ReadAsStringAsync();
    Assert.IsTrue(content.Length > 0);
}  

不确定此信息是否足以告诉我问题出在哪里,但如果需要发布更多信息,请告诉我。

最佳答案

您正在阅读来自 404 未找到请求的内容:该请求仍然有内容(告诉您找不到该内容)。因此断言内容长度超过 0 是没有意义的,因为它不区分失败和通过的测试。

您应该做的是查看状态代码 (message.StatusCode) 并确保它是 HttpStatusCode.Ok

我还建议只添加 Web Api 项目作为对单元测试项目的引用——这样您就可以直接调用方法,而不必通过 HttpClient。有关这方面的更多信息(包括测试您的路线),请查看 my blog .

关于c# - Web API 单元测试未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29657710/

相关文章:

c# - 在 C# 中传递的参数不能正常工作?内部函数使用了反射

javascript - Angular JS 错误 : [$injector:nomod] Module 'portfolioMockupApp.services' is not available

asp.net-mvc - Url.RouteUrl 在 MVC 5 中没有获得 API 路由

javascript - AngularJS,MVC。未知提供者 : $ScopeProvider <- $Scope <- userCtrl

c# - 为什么 .NET API 浏览器示例是用 C++ 而不是 C# 编写的?

c# - 如何避免在 appsettings.json 中存储密码或其他敏感数据

c# - visual studio中的 "File has no header"构建警告是什么意思

javascript - 单元测试中的去抖函数 'not a function'

visual-studio - Microsoft TestTools 的 UnitTesting 和 NUnit 之间有什么区别?

entity-framework - 使用 OData 进行事务性批处理