2

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.

Narek
  • 38,779
  • 79
  • 233
  • 389
  • 2
    Possible duplicate of [How do I use Assert to verify that an exception has been thrown?](https://stackoverflow.com/questions/933613/how-do-i-use-assert-to-verify-that-an-exception-has-been-thrown) – scharette Jun 12 '18 at 12:31
  • 2
    This is not a duplicate. See the answer below. – Narek Jun 13 '18 at 05:58

2 Answers2

5

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

Assert.That(() => winDetector.DoMove(move), 
                  Throws.TypeOf<Exception>());
Narek
  • 38,779
  • 79
  • 233
  • 389
0

Assert.Throws<Exception> is the right way to do this:

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

The () => part is necessary because the Assert.Throw<>() method will takes a TestDelegate which can be a lambda function but not an arbitrary unwrapped function.

Assert.Throws<>() should be preferred to Assert.That<>() because it more succinctly and specifically species what is being asserted.


Note: this method does not appear in Unity's documentation for the Assert class, however Unity appears to be using an NUnit derived Assert class documented here. Because this is undocumented it may not be stable in future versions.

Jack Aidley
  • 19,439
  • 7
  • 43
  • 70