如何使用Moq测试ServiceStack服务

我有一个使用ServiceStack创建的rest服务,使用nHibernate作为从SqlCe数据库获取数据的方法。 我一直在尝试使用nUnit和Moq编写一些unit testing – 我已经成功地模拟了nHibernate实现以返回null,无效对象等等 – 但我的测试总是在调用基类来设置HttpStatus等时抛出NullReferenceException

 public List  Get (ParameterAll parameterAll) { List  parameterResponseList = new List  (); try { List  parameterDomainObjectList = _ParameterDao.getAllParameters (); foreach (ParameterDomainObject parameterDomainObject in parameterDomainObjectList) { parameterResponseList.Add (parameterDomainObject.ToDto ()); } } catch (WebServiceException webEx) { Debug.WriteLine ("WebServiceException.ErrorCode " + webEx.ErrorCode); Debug.WriteLine ("WebServiceException.ErrorMessage " + webEx.ErrorMessage); Debug.WriteLine ("WebServiceException.ResponseStatus " + webEx.ResponseStatus); Debug.WriteLine ("WebServiceException.StatusCode " + webEx.StatusCode); Debug.WriteLine ("WebServiceException.StatusDescription " + webEx.StatusDescription); Debug.WriteLine ("WebServiceException.ErrorCode " + webEx.ErrorCode); } catch (DomainObjectNotFoundException domainObjectNotFoundException) { base.Response.StatusCode = (int) HttpStatusCode.NotFound; base.Response.AddHeader ("Reason", domainObjectNotFoundException.Message); } catch (Exception exception) { Debug.WriteLine ("Exception: " + exception.Message); base.Response.StatusCode = (int) HttpStatusCode.InternalServerError; base.Response.AddHeader ("Reason", exception.Message); } /* Always throws an exception here, or anywhere base.Response is called */ base.Response.StatusCode = (int) HttpStatusCode.OK; base.Response.AddHeader ("Reason", Strings.ParameterRestResponse_Get_OK); return parameterResponseList; } 

使用RestClient和Firefox进行测试时,该服务工作正常,当我注释掉base.Response代码时,我猜我只是在unit testing中没有正确设置?

  [Test] public void Test_Method_Get_AllParameters_Unsucessful () { Mock  mockedRequestContext = new Mock(); mockedRequestContext.SetupGet(f => f.AbsoluteUri).Returns("http:/localhost:8080/parameters/all"); Mock mockedParameterDao = new Mock(); mockedParameterDao.Setup (returns => returns.getAllParameters ()).Returns (new List  ()); Assert.IsNotNull (mockedParameterDao); ParameterRestService service = new ParameterRestService(mockedParameterDao.Object) { RequestContext = mockedRequestContext.Object }; List  parameterDtos = service.Get (new ParameterAll ()); } 

看起来你只需要模拟Service类的Response属性。 它没有setter而受到保护,但是你应该可以模仿它做类似……

  Mock mockedRequestContext = new Mock(); Mock mockedResponse = new Mock(); mockedRequestContext.SetupGet(f => f.AbsoluteUri).Returns("http:/localhost:8080/parameters/all"); mockedRequestContext.Setup(f => f.Get()).Returns(mockedResponse.Object);