views:

146

answers:

4

So, i'm new to unit testing, and even more so to test first development. Is it valid for me to have just a single assert.isTrue statement in my unit test where I pass in my method and a valid parameter, and compare it to the known good answer?

Method

public static string RemoveDash(string myNumber)
    {
        string cleanNumber = myNumber.Replace("-","");
        return cleanNumber;
    }

Test

[TestMethod()]
    public void TestRemoveDash()
    {
        Assert.IsTrue(RemoveDash("50-00-0")=="50000");
    }
+10  A: 

That's pretty valid if it tests the functionality of your method, which it very much seems to be doing.

Might consider using Equals here instead, but it doesn't really matter. Also, I know this is a test example, but always make sure to test cases where the input is not what is expected as well as whatever other valid forms it can come in (this can be in the same test method or a different one depending on your preference)

AHungerArtist
Another reason to prefer Assert.Equals in this case is that you will get useful feedback when it fails and not have to think as much to debug. (i.e., something like "expected '50000' but was '5000-0'" instead of "expected true but was false"). Cheers
Berryl
+2  A: 

This seems perfectly valid - however, why not include a few other tests in that method, along the same lines but testing that e.g. RemoveDash("-") == "" and RemoveDash("-5") == "5" etc?

Will A
Thanks for the input Will. Thats an easy change to implement and remember to do in the future.
Jesse McCulloch
+10  A: 

Testers sometimes read our tests so I attempt to make them as readble as possible. I would prefer to use the following, rather than the single Assert:

[TestMethod()]
public void TestRemoveDash()
{
    string expected = "50000";
    string actual = RemoveDash("50-00-0");
    Assert.AreEqual(expected,actual);
}
fletcher
Thanks fletcher. I can see how that makes it easier to read.
Jesse McCulloch
+1 I wouldn't use local variables for something this short, but AssertEquals() or the equivalent is generally helpful, since it will (usually) print both values on a test failure so it's easier to figure out what the problem is.
tc.
+6  A: 

The only comment is to use Assert.AreEqual instead of Assert.IsTrue:

Assert.IsAreEqual("50000", RemoveDash("50-00-0"));

The reason for that is that if the test fail the error message you get is more descriptive of what was meant to happen and what actually did happen. A message that says "Expected value <50000> but was actually <50-00-0>" is a lot better than "Expected value to be true, but was false."

As a rule of thumb, whenever you find yourself wanting to use Assert.IsTrue, go through Assert methods and see if there is a better method to test your expectation (e.g. Assert.IsInstanceOfType, Assert.IsNotNull, etc).

Igor Zevaka
Thanks for the further information Igor!
Jesse McCulloch