我如何模拟ServiceStack IHttpRequest

时间:2013-04-17 15:02:14

标签: unit-testing nunit moq servicestack

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

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);
});

我的服务使用该字典项:

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 };
    }
}

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

[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。因此测试失败了。有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

我认为应该这样做。

[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);    
}