本文介绍了如何模拟ServiceStack IHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用请求过滤器为将项目注入IHttpRequest.Items的服务进行单元测试:

I'm trying to get a unit test working for a service that is injecting items into the IHttpRequest.Items, using a request filter:

this.RequestFilters.Add((req, res, dto) =>
{
    // simplified for readability...
    var repo = container.Resolve<IClientRepository>();
    var apiKey = req.Headers["ApiKey"];

    // lookup account code from api key
    var accountcode = repo.GetByApiKey(apiKey);
    req.Items.Add("AccountCode", accountCode);
});

我的服务使用该词典项:

My service uses that dictionary item:

public class UserService : AppServiceBase
{
    public IUserServiceGateway UserServiceGateway { get; set; }

    public object Any(UserRequest request)
    {
        var accountCode = base.Request.Items["AccountCode"].ToString();
        var user = UserServiceGateway.GetUserByUsername(request.Name);

        return new UserResponse { User = user };
    }
}

我的测试需要以某种方式模拟请求,并插入该帐户代码项:

My test needs be somehow to mock the request, and insert that account code item:

[Test]
public void ValidUsernameReturnUser()
{
    // arrange 
    var gateway = new Mock<IUserServiceGateway>();
    gateway.Setup(s => s.GetUserByUsername(It.IsAny<string>()))
            .Returns(new UserAccountDTO { Forename = "John", Surname = "Doe" });

    var service = new UserService {
        UserServiceGateway = gateway.Object,
        RequestContext = new MockRequestContext(),
        //Request = has no setter
    };

    // request is this case is null
    base.Request.Items.Add("AccountCode", "DEF456");

    // act
    var response = (UserResponse)service.Any(new UserRequest { Name = "test" });

    // assert
    Assert.That(response.Result, Is.Not.Null);    
}

服务本身接受模拟的RequestContext,但不接受Request.因此,测试失败.有更好的方法吗?

The service itself accepts a mocked RequestContext, but not a Request. The test therefore fails. Is there a better way to do this?

推荐答案

我认为应该这样做.

[Test]
public void ValidUsernameReturnUser()
{
    // arrange 
    var mockRequestContext = new MockRequestContext();
    //add items to Request
    mockRequestContext.Get<IHttpRequest>().Items.Add("AccountCode", "DEF456");
    var gateway = new Mock<IUserServiceGateway>();
    gateway.Setup(s => s.GetUserByUsername(It.IsAny<string>()))
            .Returns(new UserAccountDTO { Forename = "John", Surname = "Doe" });

    var service = new UserService {
        UserServiceGateway = gateway.Object,
        RequestContext = new MockRequestContext(),
    };

    // act
    var response = (UserResponse)service.Any(new UserRequest { Name = "test" });

    // assert
    Assert.That(response.Result, Is.Not.Null);    
}

这篇关于如何模拟ServiceStack IHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 04:15