Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing - should I split up tests or have a single test?

I hope this doesn't come across as a stupid question but its something I have been wondering about. I wish to write unit test a method which contains some logic to check that certain values are not null.

public void MyMethod(string value1, string value2)
{
    if(value1 != null)
    {
     //do something (throw exception)
    }

    if(value2 != null)
    {
     //do something (throw exception)
    }

    //rest of method
}

I want to test this by passing null values into the method. My question is should I create a unit test for each argument or can I create one unit test which checks what happens if I set value1 to null and then checks what happens if I set value2 to null.

i.e.

[TestMethod]
public void TestMyMethodShouldThrowExceptionIfValue1IsNull()
{
    //test
}

[TestMethod]
public void TestMyMethodShouldThrowExceptionIfValue2IsNull()
{
    //test
}

or

[TestMethod]
public void TestMyMethodWithNullValues()
{
  //pass null for value1
  //check

  //pass null for value2
  //check
}

Or does it make any difference? I think I read somewhere that you should limit yourself to one assert per unit test. Is this correct?

Thanks in advance Zaps

like image 553
Riain McAtamney Avatar asked Mar 01 '10 12:03

Riain McAtamney


People also ask

Should unit tests only test one method?

This guideline is much more aggressive and recommended if you work in a test driven manner rather than write the tests after the code has been written. The main goal here is better code coverage or test coverage.

Should unit tests be in a separate file?

We have a requirement that the unit testing file need to be separate with the source file in project building. It means we must not do this for testing the source file.

Should unit tests have multiple asserts?

Multiple asserts are good if you are testing more than one property of an object simultaneously. This could happen because you have two or more properties on an object that are related. You should use multiple asserts in this case so that all the tests on that object fail if any one of them fails.


1 Answers

You should write a unit test for each test case (assertion) to avoid Assertion Roulette.

like image 126
Mark Seemann Avatar answered Oct 23 '22 11:10

Mark Seemann