Zap*_*ica 4 c# authentication integration-testing asp.net-web-api
我正忙着用asp.net web api设计一个web服务.我想开始对每个控制器进行单元测试.
到目前为止,这是我的测试类:
[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服务使用令牌身份验证.所以我有些人需要模拟身份验证过程.
所以我想我可能不会让用户通过Http请求进行测试吗?即,而不是测试控制器我只是做一个http请求并检查其答案?
测试它的更简单/更好的方法是什么?
在ASP.NET Web API中,身份验证在调用控制器之前在管道中发生,因此您需要为此编写一些集成测试.我将带您了解如何在我的在线课程中使用Outside-In TDD,但这里有它的要点:
这是使用内存中HTTP请求针对资源的集成测试.此测试不使用网络:
[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);
    }
}
如您所见,它为请求的HTTP标头添加了"Bearer"标记.这个SimpleWebToken类只是我为这个场合编写的一个自定义类,但是你可以用一个更好的类替换它来创建一个正确的身份验证令牌.
如果您更喜欢其他身份验证方案(例如"基本"或"摘要"),则可以相应地设置"授权"标头.
| 归档时间: | 
 | 
| 查看次数: | 1704 次 | 
| 最近记录: |