Non-empty test methods in JUnit 4

I would like the JUnit 4 test class to implement the same interface as its test class. Thus, as the interface changes (and it will be, we will be in an early development), the compiler ensures that the corresponding methods are added to the test class. For instance:

public interface Service { public String getFoo(); public String getBar(); } public class ServiceImpl implements Service { @Override public String getFoo() { return "FOO"; } @Override public String getBar() { return "BAR"; } } public class ServiceTest implements Service { @Override @Test public String getFoo() { //test stuff } @Override @Test public String getBar() { //test stuff } } 

When I try to do this, I get an error: "java.lang.Exception: the getFoo () method must be invalid", presumably because the test methods should return a void. Does anyone know about this?

+4
source share
2 answers

I have to admit that this is a neat trick, although it does not scale very well for several test cases.

In any case, you can use a custom runner. For instance:

 @RunWith(CustomRunner.class) public class AppTest { @Test public int testApp() { return 0; } } public class CustomRunner extends JUnit4ClassRunner { public CustomRunner(Class<?> klass) throws InitializationError { super(klass); } protected void validate() throws InitializationError { // ignore } } 
+7
source

A more natural way would probably be to use a code coverage tool such as Cobertura . It integrates perfectly with JUnit and shows cases when your tests may be insufficient in some cases (there are many cases when such a tool does not catch).

+1
source

All Articles