Dylan Beattie
Dylan Beattie

Reputation: 54140

How can I test WebServiceException handling using ServiceStack?

I have a controller method something like:

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

The API instance is a wrapper around a ServiceStack JsonClient, and I've got methods on my ServiceStack service that will throw 409 conflicts like:

throw HttpError.Conflict(StatusMessages.USERNAME_NOT_AVAILABLE);

In my unit testing, I'm using Moq to mock the IApi, but I cannot work out how to 'simulate' the WebServiceException that's thrown by the JsonClient when the remote server returns a 409. My unit test code looks like this:

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

However, there's a couple of fields - ErrorMessage, ErrorCode, ResponseStatus - that are read-only and so can't be set in my unit test.

How can I get ServiceStack to throw the same WebServiceException within a unit test that's being thrown when the client receives an HTTP error response from a server?

Upvotes: 2

Views: 1307

Answers (1)

StuartLC
StuartLC

Reputation: 107267

Looking at the source code for WebServiceException, it seems that ErrorMessage, ErrorCode, and ResponseStatus are extracted from ResponseDto, which is publically settable.

And it looks like there is a CreateResponseStatus(string errorCode, string errorMessage, IEnumerable<ValidationErrorField> validationErrors) method here which will help creating this?

Upvotes: 1

Related Questions