C# – Assert that a string is not null or empty with NUnit

If you want to Assert that a result string in a NUnit test is not null or empty, use:

Assert.That(string.IsNullOrEmpty(result), Is.False, "Result string must not be null or empty");

Leave a Reply

Your email address will not be published. Required fields are marked *

2 comments

  1. Mark Hone says:

    Hi Roel,

    I believe you can also do the following (in NUnit 3 at least):
    Assert.That(result, Is.Not.Null.Or.Empty, “Result string must not be null or empty”);

    Further details:
    https://github.com/nunit/nunit/wiki/Breaking-Changes

    Thanks,

    Mark

  2. G Helyar says:

    Regarding Mark’s comment, that should be
    Assert.That(result, Is.Not.Null.And.Not.Empty);

    Assert.That(“”, Is.Not.Null.Or.Empty); passes because the empty string is not null, or is empty. In fact, because Is.Not.Null passes, the Or.Empty isn’t even hit.

    !string.IsNullOrEmpty is equivalent to !(s == null || s == “”), which is equivalent to s != null && s != “”
    Is.Not.Null.Or.Empty is equivalent to !(s == null) || s == “”, which is equivalent to s != null || s == “”

    This can also be used for collections.