Question

I have a snippet as follows

public void setTarget(String target) throws TargetException{
   if(target = null){
      throw new TargetException();
   }
   this.target = target;
}

public void getTarget(){
   return this.target;
}

I am unit testing the above snippet

@Test(expected = TargetException.class)
public void testTargetSetting() throws TargetException{
   //For coverage of code in if loop
   String target = null;
   MyBean.setTarget(target);
   //For coverage of code in else loop
   target="abc";
   MyBean.setTarget(target);
}

Now the problem with above code is the code coverage for class to be tested shows 100% that is the method setTarget. It goes in both if and else blocks. But the coverage of test class method ie testTargetSetting is not covered. It is always shown in red.

I am using Emma for Code coverage. Any idea how the code coverage for both the actual class method and test class method can be satisfied.

Note: The code given above is only for illustration.

Was it helpful?

Solution

Well, your test-Method is not tested completely because you run the test that throws the exception before the other test. Your test framework expects the exception, so the test does not fail. However, the lines

target="abc";
MyBean.setTarget(target);

are not executed.

Three additional thoughts:

  • there are two test cases in one test method - you should have one test method that tests the exception and one that tests the happy path
  • As mentioned in spookyjon's answer, code coverage tools are usually not used to check for the coverage of test methods.
  • If the code after the exception would run, you would achieve coverage. But since there are no assertions, you wouldn't actually test anything apart from the fact that no unexpected exception occured. Tests without assertions are not particularly meaningful.

OTHER TIPS

To have coverage for the test class, you would have to write a test class for your test class. To have coverage for that class, you would have to write a test class for the test class for your test class.

Simply put, tools like Emma aren't meant to show coverage on your test classes. They use your test classes to show coverage on your regular classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top