如何编写针对ASP.NET Web API的集成测试 [英] How to write integration test for asp.net web api
问题描述
我正忙于使用asp.net Web API设计Web服务.我想开始在每个控制器上进行单元测试.
I am busy design a web service with asp.net web api. 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();
}
}
但是我的Web服务使用令牌身份验证.因此,我提出了一些需要模拟身份验证过程的方法.
But my web service makes use of token authentication. So I some how need to emulate the authentication process.
所以我在想我可能不是让Http Request的用户进行测试吗?即不是测试控制器,我只是发出一个HTTP请求并检查其答案?
So I was thinking my i not maybe make user of a Http Request to test it? Ie instead of testing the controller I just make a http Request and check its answer?
进行测试的更简便/更好的方法是什么?
What is the easier / better way to go about testing it?
推荐答案
在ASP.NET Web API中,身份验证发生在调用Controllers之前的管道中,因此您需要为此编写一些集成测试.我会在外部TDD 的在线课程中指导您完成该操作,但是这是要点:
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. I walk you through how to do that in my on-line course on Outside-In TDD, but here's the gist of it:
这是使用内存HTTP 请求针对资源进行的集成测试.此测试不使用网络:
Here's an Integration Test against a resource using in-memory HTTP requests. 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);
}
}
如您所见,它将"Bearer"令牌添加到请求的HTTP标头中. SimpleWebToken
类只是我为此编写的一个自定义类,但是您可以将其替换为一个更好的类,该类可以创建正确的身份验证令牌.
As you can see, it adds a "Bearer" token to the HTTP headers of the request. 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.
如果您喜欢其他身份验证方案(例如基本"或摘要"),则可以相应地设置授权标头.
If you prefer a different authentication scheme (such as Basic or Digest), you can set the Authorization header accordingly.
这篇关于如何编写针对ASP.NET Web API的集成测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!