Easily replacing Assert.IsTrue statements

Wednesday, Feb 12, 2014 1 minute read Tags: unit-testing testing

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:


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:


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.