我想让我的ServiceStack服务可测试。
目前我有:
[RequireFormsAuthentication]
public object Delete(DeleteRequest request)
{
var originalRequest = (HttpRequest)Request.OriginalRequest;
var identity = originalRequest.RequestContext.HttpContext.User.Identity;
return othercode(identity);
}
RequireFormsAuthentication的位置
public class RequireFormsAuthenticationAttribute : RequestFilterAttribute
{
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
var originalRequest = (HttpRequest)req.OriginalRequest;
var identity = originalRequest.RequestContext.HttpContext.User.Identity;
if (!identity.IsAuthenticated)
{
res.StatusCode = (int)HttpStatusCode.Forbidden;
res.EndServiceStackRequest(skipHeaders: true);
}
}
}
我嘲笑了' othercode()'使用的所有依赖项。剩下的就是基类服务中的东西了。是否存在一种模式/策略/方法/我缺少的东西使得这个微不足道?
答案 0 :(得分:7)
以下是使用Moq进行测试的方法。此服务在查询字符串中查找“键”和“值”,并在请求DTO中查找另一个参数。该服务根据给定的值返回字符串响应。
[Test]
public void MyTest()
{
var mockRequestContext = new Mock<IRequestContext>();
var mockedHttpRequest = new Mock<IHttpRequest>();
NameValueCollection querystring = new NameValueCollection();
querystring.Add("myKey", "myValue");
mockedHttpRequest.SetupGet(r => r.QueryString).Returns(querystring);
mockRequestContext.Setup(x => x.Get<IHttpRequest>()).Returns(mockedHttpRequest.Object);
AboutService service = new AboutService
{
RequestContext = mockRequestContext.Object,
};
AboutResponse response = (AboutResponse)service.Any(new About
{
Company = "myOtherValue",
});
Assert.AreEqual(0, response.QueryResult);
Assert.AreEqual("validResponse", response.Version);
}
答案 1 :(得分:2)
我为不使用moq而道歉...已经使用RhinoMocks完成了一些操作。我认为这个概念应该转移到moq。 This可能是一个很好的资源,也可能是this。
无论如何,我认为下面的测试代码应该让你入门。你对模拟Request.OriginalRequest
的接缝是用模拟对象替换Service.RequestContext
。然后你只需要模仿除此之外的一切。这将是很多'嘲弄',如果你重复自己'你是在嘲笑我'每次你嘲笑一个课程,这几乎是愉快的。
[Test]
public void testsomethign()
{
var mockedRequestContext = MockRepository.GenerateMock<IRequestContext>();
var mockedHttpRequest = MockRepository.GenerateMock<IHttpRequest>();
var mockedOriginalRequest = MockRepository.GenerateMock<HttpRequestBase>();
var mockedOriginalRequestContext = MockRepository.GenerateMock<RequestContext>();
mockedOriginalRequest.Stub(x => x.RequestContext).Return(mockedOriginalRequestContext);
mockedHttpRequest.Stub(x => x.OriginalRequest).Return(mockedOriginalRequest);
mockedRequestContext.Stub(x => x.Get<IHttpRequest>()).Return(mockedHttpRequest);
var service = new ServiceTests()
{
RequestContext = mockedRequestContext
};
service.Delete(new DeleteRequest());
}
答案 2 :(得分:2)
请务必查看命名空间:ServiceStack.ServiceInterface.Testing。
在那里你可以找到一个MockRequestContext,你可以使用如下:
var mockContext = new ServiceStack.ServiceInterface.Testing.MockRequestContext();
//do stuff to set it up if desired...
AboutService service = new AboutService
{
RequestContext = mockContext
};