Pergunta

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);
Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top