Question

I want to substitute an exception and it's fields.

Something like that:

var webExcetion = Substitute.For<WebException>();
webExcetion.Response.Returns(httpWebResponse);
substituteForHttp.GetResponse(Arg.Any<string>()).Returns(x => { throw webExcetion; });

This code throws Castle.Proxies.ExceptionProxy or NSubstitute.Exceptions.CouldNotSetReturnException by NSubstitute.

How can I do that?

Was it helpful?

Solution

The WebException class does not have virtual members, so NSubstitute can not do much with it (it works by creating an instance of a derived type using Castle DynamicProxy, then changes the instance to work as a substitute by overriding all the virtual members).

In this case it should be fine to work around this problem by using a real WebException:

WebException webException = 
    new WebException("test", null, webExceptionStatus, httpWebResponse);

This will set the Response property to httpWebResponse as required.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top