Search code examples
regexnunitassert

How can I use regex wildcard in assertion?


I am trying to do a general Assert.AreEqual call on some details in a table header, however I am struggling figuring out how to successfully format the expected results. The return value on the GetTableHeader call is as follows:

"× •••\r\nAcme Health Fund\r\nBalance Date: 9/27/2017"

I ONLY want to assert that the Acme Health Fund text is present. My current call is this:

Assert.AreEqual("/.*Acme Health Fund.*/" , GetTableHeader() );

How can I format my first parameter in the AreEqual call to ONLY expect "Acme Health Fund"?


Solution

  • NUnit 3 has a much more powerful constraint syntax, I would recommend you use that instead. New features are added to the constraint syntax, not to the old Assert.AreEqual style.

    Regex is overkill for what you want, all you need to do is assert that the string Does.Contain the name.

    Assert.That(GetTableHeader(), Does.Contain("Acme Health Fund"));
    

    If you really need to use a regex, first you don't need to surround it in the slashes and you use the Does.Match syntax.

    Assert.That(GetTableHeader(), Does.Match(".*Acme Health Fund.*"));
    

    Note the fix in your regex.