Monday, 16 August 2010

Response to "Two different ways to create bad logic in unit tests"

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 code base into the unit test anyway.  

As an example directly from Roy's blog consider the following code:

   1: [TestMethod]



   2: public void SomeTest()



   3: {



   4:   string user = "user";



   5:   ComponentUnderTest cut = new ComponentUnderTest();



   6:   string result = cut.SayHello(user);



   7:   string expected = "hello " + user;



   8:   Assert.AreEqual(expected,result);



   9: }




Thinking this through, it makes perfect sense, the following could be a better test:





   1: [TestMethod]



   2: public void SomeTest()



   3: {



   4:    string user = "user";



   5:    ComponentUnderTest cut = new ComponentUnderTest();



   6:    string result = cut.SayHello(user);



   7:    string stringPrefix = "Hello ";



   8:    Assert.IsTrue(result.StartsWith(stringPrefix, result);



   9:    Assert.IsTrue(result.EndsWith(string.Format(" {0}", user), result);



  10:    Assert.AreEqual(stringPrefix.Length + user.Length, result.Length);



  11: }




Could this be the answer?  It certainly removes any possible duplicated logic that may hide issues in the string manulipation, but would it be workable in a more complex example?

No comments:

Post a Comment