How do I use Assert (or other Test class?) to verify that an exception has been thrown?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
My preferred method for implementing this is to write a method called Throws, and use it just like any other Assert method. Unfortunately, .NET doesn't allow you to write a static extension method, so you can't use this method as if it actually belongs to the build in Assert class; just make another called MyAssert or something similar. The class looks like this:
That means that your unit test looks like this:
Which looks and behaves much more like the rest of your unit test syntaxes.
As an alternative you can try testing exceptions are in fact being thrown with the next 2 lines in your test.
Since you mention using other test classes, a better option than the
ExpectedException
attribute is to use Shoudly's Should.Throw.Let's say we have a requirement that the customer must have an address to create an order. If not, the
CreateOrderForCustomer
method should result in anArgumentException
. Then we could write:This is better than using an
ExpectedException
attribute because we are being specific about what should throw the error. This makes requirements in our tests clearer and also makes diagnosis easier when the test fails.Note there is also a
Should.ThrowAsync
for asynchronous method testing.Be wary of using ExpectedException, as it can lead to several pitfalls as demonstrated here:
http://geekswithblogs.net/sdorman/archive/2009/01/17/unit-testing-and-expected-exceptions.aspx
And here:
http://xunit.github.io/docs/comparisons.html
If you need to test for exceptions, there are less frowned upon ways. You can use the try{act/fail}catch{assert} method, which can be useful for frameworks that don't have direct support for exception tests other than ExpectedException.
A better alternative is to use xUnit.NET, which is a very modern, forward looking, and extensible unit testing framework that has learned from all the others mistakes, and improved. One such improvement is Assert.Throws, which provides a much better syntax for asserting exceptions.
You can find xUnit.NET at github: http://xunit.github.io/
In a project i´m working on we have another solution doing this.
First I don´t like the ExpectedExceptionAttribute becuase it does take in consideration which method call that caused the Exception.
I do this with a helpermethod instead.
Test
HelperMethod
Neat, isn´t it;)
Check out nUnit Docs for examples about: