Question

I want to write a unit test to ensure that I get a WebException with a 404 status code thrown from a particular method.

The WebException bit is easy:

[Test]
[ExpectedException(typeof(WebFaultException))]
public void CheckForWebFaultException()
{
  var myClass = new MyClass();
  myClass.MyMethod();
}

However this could be a 404, a 400, 401 or any other of the myriad of other http codes.

I could do a try/catch/Assert.True but this feels like a hack. Is there a way to Assert against a property of the thrown exception?

Something like

Assert.Throws(typeof(WebFaultException), myClass.MyMethod(), wfx => wfx.StatusCode == HttpStatusCode.NotFound);
Was it helpful?

Solution

I was on the right lines, Assert.Throws actually returns the exception which was thrown.

[Test]
public void CheckForWebFaultException()
{
  var myClass = new MyClass();  
  var ex = Assert.Throws<WebFaultException>(() => myClass.MyMethod());
  Assert.AreEqual(HttpStatusCode.NotFound, ex.StatusCode);    
}

Note that I've taken out the [ExpectedException(typeof(WebFaultException))] as the exception is now handled and the test will fail if this is left in.

Assert.Throws ensures that the exception was thrown by myClass.MyMethod() and the second assert checks the status code.

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