Today I read Roy Osherove’s blog post “Two Different ways to create bad logic in unit tests“. It’s an interesting article that covers logic included in many unit tests, is it acceptable to compare a returned string value using a comparison value built via string concatenation? It is perfectly possible that an issue introduced by the concatenation process is duplicated in both the code and the unit test – more often than not the logic has been cut/pasted from the codebase into the unit test anyway.
As an example directly from Roy’s blog consider the following code:
[TestMethod] public void SomeTest() { string user = "user"; ComponentUnderTest cut = new ComponentUnderTest(); string result = cut.SayHello(user); string expected = "hello " + user; Assert.AreEqual(expected,result); }
Thinking this through, it makes perfect sense, the following could be a better test:
[TestMethod] public void SomeTest() { string user = "user"; ComponentUnderTest cut = new ComponentUnderTest(); string result = cut.SayHello(user); string stringPrefix = "Hello "; Assert.IsTrue(result.StartsWith(stringPrefix, result); Assert.IsTrue(result.EndsWith(string.Format(" {0}", user), result); Assert.AreEqual(stringPrefix.Length + user.Length, result.Length); }
Could this be the answer? It certainly removes any possible duplicated logic that may hide issues in the string manipulation, but would it be workable in a more complex example?
Today I realised that I’d forgotten how spoilt I am using Resharper and dotCover to run my unit tests. Put another way I’d forgotten how badly Visual Studio plays with any other unit test frameworks other than MS Test! I’m used to and really like the fluent API style of NUnit’s Assert.That(…) syntax so having to fall back to MS Test always feels like a step back. If you ever find yourself in a situation . . .
When I first started looking into Windows Workflow one of the first things that I liked about it was how it separated responsibilities. The workflow was responsible for handling the procedural logic with all its conditional statements, etc. Whilst individual code activities could be written to handle the business logic processing; created in small easily re-usable components. To try and realise my original perception this series of blog posts will cover the unit testing of . . .