【问题标题】:How can I test WebServiceException handling using ServiceStack?如何使用 ServiceStack 测试 WebServiceException 处理?
【发布时间】:2014-01-08 19:50:41
【问题描述】:

我有一个类似的控制器方法:

public class FooController : Controller {

    private IApi api;

    public FooController(IApi api) { 
        this.api = api;
    }

    public ActionResult Index() {
        try {
            var data = api.GetSomeData();
            return(View(data));
        } catch(WebServiceException wsx) {
            if(wsx.StatusCode == 409) return(View("Conflict", wsx));
            throw;
        }
    }
}

API 实例是 ServiceStack JsonClient 的包装器,我的 ServiceStack 服务上有一些方法会引发 409 冲突,例如:

throw HttpError.Conflict(StatusMessages.USERNAME_NOT_AVAILABLE);

在我的单元测试中,我使用 Moq 来模拟 IApi,但我不知道如何“模拟”当远程服务器返回 409 时 JsonClient 抛出的 WebServiceException。我的单元测试代码如下所示:

var mockApi = new Mock<IApi>();
var ex = HttpError.Conflict(StatusMessages.USERNAME_NOT_AVAILABLE);
var wsx = new WebServiceException(ex.Message, ex);
wsx.StatusCode = (int)HttpStatusCode.Conflict;
wsx.StatusDescription = ex.Message;

mockApi.Setup(api => api.GetSomeData()).Throws(wsx);

var c = new FooController(mockApi.Object);
var result = c.Index() as ViewResult;
result.ShouldNotBe(null);
result.ViewName.ShouldBe("Conflict");

但是,有几个字段 - ErrorMessageErrorCodeResponseStatus - 是只读的,因此无法在我的单元测试中设置。

当客户端从服务器接收到 HTTP 错误响应时,如何让 ServiceStack 在单元测试中抛出相同的 WebServiceException?

【问题讨论】:

    标签: c# web-services rest servicestack moq


    【解决方案1】:

    查看WebServiceExceptionsource code,似乎ErrorMessageErrorCodeResponseStatus是从ResponseDto中提取出来的,可以公开设置。

    看起来有一个CreateResponseStatus(string errorCode, string errorMessage, IEnumerable&lt;ValidationErrorField&gt; validationErrors) 方法here 可以帮助创建这个?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 2012-03-25
      • 2012-09-29
      • 2011-08-09
      • 1970-01-01
      相关资源
      最近更新 更多