c# Xunit, Assert.Throws fails when expected exception raised

Kelson Ball picture Kelson Ball · Mar 22, 2016 · Viewed 11.4k times · Source

EDIT: There is a similar question here, but the solutions only suggest workarounds and provide no insights into the cause of the issue or how to fix it. This question may still be a duplicate.

EDIT 2: It turns out this issue is only happening during debug, although it was not happening earlier. After replacing (TCheck)null with null as TCheck the tests pass when ran but throw an exception when debugged.

ORIGINAL POST: I have a method in a unit test that looks like this

internal void EqualityAssert<TCheck, TEquatable>(TEquatable item, ... ) 
    where TCheck : class, IEquatable<TEquatable>, TEquatable
{

    // Various equality assertions that are passing
    // ...

    // A == null       
    Assert.Throws<NullReferenceException>(
    () => ((IEquatable<TEquatable>)item).Equals((TCheck)null));            
}

This method is called by various unit tests, and each of those tests are failing because an "Unhandled NullReferenceException was encountered" exactly where it is expected.

Assert.Throws was working properly for me earlier but I haven't been able to figure out what changed to break it.

Answer

user1829319 picture user1829319 · Nov 30, 2016

Better to use this pattern:

[Fact]
public void Divide_TwoNumbers_ExpectException()
{
    var sut = new Calculator();
    var exception = Record.Exception(() => sut.Divide(10, 0));
    Assert.IsType(typeof(DivideByZeroException), exception);
}