2

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?

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.