S h o r t S t o r i e s

// Tales from software development

NUnit StringAssert.DoesNotContain()

with one comment

I’ve just finished writing a small test application that needed to verify that an error message did not occur in an output file.

I looked through the list of methods implemented on the NUnit StringAssert class and couldn’t see anything that would suffice. There is a Contains() but not a DoesNotContain() or a NotContains(). That’s a shame because although Contains() is a standard string method and DoesNotContain() isn’t, at least in code you can easily negate the result, e.g.:

if (!stringValue.Contains("something"))

but you can’t do this with an NUnit assertion because the result is an exception not a boolean value.

First I used a quick fix that consisted of testing whether the string value contained the error message and throwing an NUnit AssertionException if it did. But this wasn’t pretty and I started looking at how to implement the assertion properly using NUnit’s extensibility features.

Although the correct way to implement the new assertion is to write a custom constraint I found there was another way to get the functionality I needed. Using Reflector on the NUnit.Framework assembly, I could see that the StringAssert.Contains() method is just a wrapper for this:

Assert.That(actual, new SubstringConstraint(expected), message)

Looking down the list of Constraint classes I noticed the NotConstraint which, as implied by its name, negates the result of another constraint. So, I didn’t need to implement anything at all, I just needed this:

Assert.That(actual, new NotConstraint(new SubstringConstraint(expected)), message);


Written by Sea Monkey

August 17, 2010 at 8:00 am

Posted in Development

Tagged with

One Response

Subscribe to comments with RSS.

  1. The NUnit framework includes StringAssert.DoesNotContain() since at least version 2.5.2, though it is not documented. The following line will fail:

    StringAssert.DoesNotContain(“M”, “MyString”);

    Regards, Peter

    Peter Gluck

    December 14, 2010 at 8:08 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: