Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to have unit tests with only an assert statement?

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");
    }
like image 460
Jesse McCulloch Avatar asked Aug 16 '10 22:08

Jesse McCulloch


People also ask

Should a unit test only have one assert?

Proper unit tests should fail for exactly one reason, that's why you should be using one assert per unit test.

Do all unit tests need assert?

A test without an assert (containing only an action with a possible setup) makes sure that the process works without an exception. In any other case, the test passes.

Why is it recommended to have only one assert statement per test?

“One assertion per test” is a wise rule to keep in mind, because it helps you have tests that fail for a specific reason, and drives you to focus on a specific behavior at a time.

How many asserts should a unit test have?

One Assertion in One Test Method To keep unit tests simple, it is best to include a single assertion in one test method. That means, one unit test should test one use-case and no more.


2 Answers

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)

like image 109
AHungerArtist Avatar answered Oct 21 '22 01:10

AHungerArtist


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);
}
like image 40
fletcher Avatar answered Oct 21 '22 01:10

fletcher