我想让我的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()’使用的所有依赖项,剩下的就是基类Service中的东西.是否有一种模式/策略/方法/我缺少的东西使这个微不足道?
解决方法
我为不使用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()); }