Easily replacing Assert.IsTrue statements

Wednesday, Feb 12, 2014 1 minute read Tags: unit-testing testing
Hey, thanks for the interest in this post, but just letting you know that it is over 3 years old, so the content in here may not be accurate.

I blogged/ranted about Assert.IsTrue previously, well today I decided to work out a quick way to do bulk conversions of tests.

Well the easiest way to go about this is using a good old Regular Expression:

Assert\.IsTrue\((?<Actual>.*)\s*==\s*(?<Expected>.*)\)

That’s a regex which is ideal for using from Visual Studio, or any other tool that supports named capture groups. If you don’t have something like that you can use numerical capture groups:

Assert\.IsTrue\((.*)\s*==\s*(.*)\)

Now for the replace regex:

Assert.AreEqual(${Expected}, ${Actual})

Or for numbered capture groups:

Assert.AreEqual(${2}, ${1})

Or maybe you’re using NUnit and want to use Assert.That (which some people argue is more readable), try this out:

Assert.That(${Actual}, Is.EqualTo(${Actualy}))

Bonus, adding messages

As a friend of mine, Jason Stangroome pointed out you might also want to include a message to the assert for additional information when it’s failing, so we’d update our regex like so:

Assert.AreEqual(${Expected}, ${Actual}, "${Actual} was expected to have th evalue of " +  ${Expected})

This will add the name of the variable we are asserting.