Search code examples
c#unit-testingunity-game-engineexception

Unity unit tests - Check if the function call with an argument throws an exception


I unity I have a function to call with wrong arguments and I want to make sure that the function throw the right exception with the right message. So my function call is this:

winDetector.DoMove(move)

And it should throw and exception like this:

throw new Exception("Move is not valid.");

Looks like I should use Assert.Throws<Exception> but I don't know how. Now to both Unity and C#. How can I do this?

P.S. Assert.Throws<Exception> is not the correct way. Please see my answer below.


Solution

  • There is an elegant way to do that. Here is how it should be done:

    Assert.That(() => winDetector.DoMove(move), 
                      Throws.TypeOf<Exception>());