[英]How to write integration test for asp.net web api
I am busy design a web service with asp.net web api. 我正忙着用asp.net web api设计一个web服务。 And I want to start doing unit tests on each controller.
我想开始对每个控制器进行单元测试。
here is my test class so far: 到目前为止,这是我的测试类:
[TestClass]
public class MyDevicesControllerTest
{
[TestMethod]
public void TestValidUser()
{
MyDeviceController controller = new MyDeviceController();
var result = controller.Get();
}
[TestMethod]
public void TestInvalidUser()
{
MyDeviceController controller = new MyDeviceController();
var result = controller.Get();
}
}
But my web service makes use of token authentication. 但我的Web服务使用令牌身份验证。 So I some how need to emulate the authentication process.
所以我有些人需要模拟身份验证过程。
So I was thinking my i not maybe make user of a Http Request to test it? 所以我想我可能不会让用户通过Http请求进行测试吗? Ie instead of testing the controller I just make a http Request and check its answer?
即,而不是测试控制器我只是做一个http请求并检查其答案?
What is the easier / better way to go about testing it? 测试它的更简单/更好的方法是什么?
In ASP.NET Web API, Authentication happens in the pipeline before the Controllers are invoked, so you'll need to write some Integration Tests for that. 在ASP.NET Web API中,身份验证在调用控制器之前在管道中发生,因此您需要为此编写一些集成测试。 I walk you through how to do that in my on-line course on Outside-In TDD , but here's the gist of it:
我将带您了解如何在我的在线课程中使用Outside-In TDD ,但这里有它的要点:
Here's an Integration Test against a resource using in-memory HTTP requests. 这是使用内存中HTTP请求针对资源的集成测试。 This test doesn't use the network:
此测试不使用网络:
[Fact]
public void GetReturnsResponseWithCorrectStatusCode()
{
var baseAddress = new Uri("http://localhost:8765");
var config = new HttpSelfHostConfiguration(baseAddress);
config.Routes.MapHttpRoute(
name: "API Default",
routeTemplate: "{controller}/{id}",
defaults: new
{
controller = "Home",
id = RouteParameter.Optional
});
var server = new HttpSelfHostServer(config);
using (var client = new HttpClient(server))
{
client.BaseAddress = baseAddress;
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer",
new SimpleWebToken(new Claim("userName", "foo")).ToString());
var response = client.GetAsync("").Result;
Assert.True(
response.IsSuccessStatusCode,
"Actual status code: " + response.StatusCode);
}
}
As you can see, it adds a "Bearer" token to the HTTP headers of the request. 如您所见,它为请求的HTTP标头添加了“Bearer”标记。 The
SimpleWebToken
class is just a custom class I wrote for the occasion, but you can replace it with a better class that creates a correct authentication token. SimpleWebToken
类只是我为这个场合编写的一个自定义类,但你可以用一个更好的类替换它来创建一个正确的身份验证令牌。
If you prefer a different authentication scheme (such as Basic or Digest), you can set the Authorization header accordingly . 如果您更喜欢其他身份验证方案(例如“基本”或“摘要”),则可以相应地设置“授权”标头 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.