A Better Way to Test for Exceptions in Visual Studio
I've always argued that the only easier way to test your code than using Visual Studio Test is to not test at all. But that doesn't mean that I think Visual Studio Test is perfect.
For example, the ExpectedException attribute, when placed on a test method, lets you check to make sure that your code throws the appropriate exception when something goes horribly wrong. The problem with ExpectedException is that it applies to the whole test method, not just the "code under test." This means that if your test or production code throws that exception anywhere at all, the ExpectedException attribute will tell you that your test has passed. Unfortunately, that exception may or may not have been thrown where you actually expected it to be thrown. That's not quite what you want to test for.
You have a better alternatives: the Assert object's ThrowsException and ThrowsExceptionAsync methods. With either of those methods, you specify the exception you expect to get from your method and then pass the code you want to test (as a lambda expression) to the method.
This example checks to see if the GetCustomer method throws a NullReferenceException when the GetCustomer method is called with an empty string:
Assert.ThrowsException<NullReferenceException>(() => cust = CustomerRepository.GetCustomer(""));
This test will now pass if (and only if) this call to the GetCustomer method throws a NullReferenceException. If any other code in my test method throws that exception (or if my code throws any other kind of exception), my test will be flagged as failed. And that's exactly what I want.
Posted by Peter Vogel on 11/16/2018 at 2:53 PM