Non-void test methods in JUnit 4

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-06 13:51:06

问题


I would like a JUnit 4 test class to implement the same interface as the class its testing. This way, as the interface changes (and it will, we're in early development), the compiler guarantees that corresponding methods are added to the test class. For example:

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 this, I get an error: "java.lang.Exception: Method getFoo() should be void", presumably because test methods must return void. Anybody know of any way around this?


回答1:


I have to admit, it is a neat trick, though it doesn't scale well to multiple test scenarios.

Anyways, you can use custom runner. For example:

@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
  }
}



回答2:


A more natural way would probably be to use a code coverage tool, such as Cobertura. It integrates with JUnit nicely AND it shows you cases where your tests may be deficient in some cases (there are many cases such a tool won't catch though).



来源:https://stackoverflow.com/questions/3917560/non-void-test-methods-in-junit-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!