NUnit 2016 Throws.TypeOf

Why does this code throw an exception instead of passing the test?

public static int ThrowsSomething(string name)
{
    if (name == null)
        throw new ArgumentNullException(nameof(name), "can't be null because that silly");
    return -1;
}

[Test]
public void WindowTest()
{
    Assert.That(ThrowsSomething("dave"), Is.EqualTo(-1));
    Assert.That(ThrowsSomething(null), Throws.TypeOf<ArgumentNullException>());
}

Unit Test The session window shows the following:

WindowTest [0: 00.066] Error: System.ArgumentNullException: cannot be null because it is stupid

Visual Studio 2015 with ReSharper Ultimate 2016.3 and NUnit 3.6.1

+4
source share
1 answer

The test fails because the thrown exception is not implemented and prevents the test from executing until completion.

Use Assert.Throws<>to approve an excluded exception

[Test]
public void WindowTest() {
    Assert.That(ThrowsSomething("dave"), Is.EqualTo(-1));
    Assert.Throws<ArgumentNullException>(() => ThrowsSomething(null));
}

or use a delegate so that the exception can be caught and handled by the statement.

Assert.That(() => ThrowsSomething(null), Throws.Exception.TypeOf<ArgumentNullException>());
+6
source

Source: https://habr.com/ru/post/1676915/


All Articles