Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to ignore Possible Null Reference Exception warnings when using Assert statements?

I do not want to disable the warnings completely, just when it's in an Assert statement.

So for example if I have the following two lines

var someObject = GetObject();
Assert.IsNotNull(someObject, "someObject should not be null");
Assert.AreEqual(expectedValue, someObject.SomeProperty);

I'll get the possible null reference warning on the second line on someObject.SomeProperty. Is it possible to disable the warning when it is within a certain call, like Assert.AreEqual?

Since this is an issue with a lot of unit tests, I don't want to litter the tests with the ReSharper disable code.

Right now the only option I can think of is to change every Assert.IsNotNull call to be

var someObject = GetObject();
if(someObject == null)
{
  Assert.Fail("someObject is null");
  return;
}

Although this kind of seems to defeat the purpose of having Assert.IsNotNull in the first place. Just wondering if there is a better way.

like image 826
Brandon Avatar asked Mar 23 '12 15:03

Brandon


2 Answers

Add this to your project:

public static class AssertionsExtensions
{
    [NotNull]
    public static TSubject ShouldNotBeNull<TSubject>([CanBeNull] this TSubject source,
        [CanBeNull] string because = "", [CanBeNull] [ItemCanBeNull] params object[] reasonArgs)
    {
        source.Should().NotBeNull(because, reasonArgs);

        // ReSharper disable once AssignNullToNotNullAttribute
        return source;
    }
}

Then use it like this, for example:

            // Assert
            succeeded.Should().Be(true, "<USB loopback cable must be connected and COM port must be correct.>");
            DeviceStatus deviceStatusNotNull = testRunner.Result.ShouldNotBeNull();
            deviceStatusNotNull.DeviceAddress.Should().Be(deviceAddress);
            deviceStatusNotNull.IsInNetwork.Should().Be(true);
like image 22
bkoelman Avatar answered Oct 17 '22 00:10

bkoelman


I don't know the specific library you use, but I'd try something like

Assert.IsTrue(someObject != null);

or, for the sake of completeness,

Assert.IsNotNull(someObject, "someObject must not be null");
Assert.IsNotNull(someObject.SomeProperty, "SomeProperty must not be null either");
Assert.SomethingElse(...);
like image 171
Alex Avatar answered Oct 17 '22 01:10

Alex