Using TestCase and Should

Transcript

Tap on time to skip ahead

00:10

One of the things that usually forgotten with the whole Red, Green, Blue phase, or sometimes called Red Green Refactor Process, is the step of actually taking a look at your test code and see if it can be better. And by better, we mean is it optimized? Much like you would optimize your production code. Maybe instead of cut and pasting three lines of code, you could just make a method or function that other things can call. Or do you also look to see if it can be clear to read.

00:38

Right now, while our tests are very small, we haven’t really done too much with this particular application, we kind of want to nip any sort of these problems at the bud instead of letting them fester and create this nasty test code base that we no longer want to maintain.

00:54

One of the things you’ll see is I’ve duplicated code here to basically create an instance of the ViewModel, set the email address and then validate whether it’s true or false. I’ve created two separate methods for this. This is pretty inefficient. What we can do is we can use what is called a TestCase in Nunit to where I can pass in different parameters.

01:21

In this case, I’m going to pass in an email address as well as whether or not this should pass. Now, I’m going to set the email address to what was passed. I’m going to change my assert to AreEqual. And we want the expected to be first, which isn’t overly obvious unless you’re looking at the Intellisense. And we’re going to say vmUT.EmailIsValid. Then I’m going to get rid of this. Now, I can go in here. I can say Ben@rendr.io, true. I can say Jeff@brax.tv. I need to put in another bad case or two. Now, when we run this, we actually run four tests but with just one test method, like so.

02:33

The other thing we need to do is make sure this is readable for other people coming in. Right now, this whole given then structure doesn’t work for our names. I’m just going to go with something much easier. TestEmailIsValid. That should be clear enough to people.

02:53

The other thing, I don’t feel as those Assert.AreEqual is overly easy to read. We don’t talk like this in real English. One of the things I like to add is a NuGet package called Should. It makes for fluent style assertions. If I add this NuGet package, what I can now say is vmUT.EmailIsValid ShouldEqual(shouldPass). Now that’s a bit cleaner and easier to read.

03:34

That is a real key thing with unit tests. We don’t want people to open up our unit test and immediately sigh because they have no clue what is going on. While it might take some extra time to write some of this stuff out, it will make it much faster and easier for people to read. Reading is more important than writing. This is how we can optimize and refactor our unit tests as we build them out.