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.
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: