JUnit 4 中的非 void 测试方法
我希望 JUnit 4 测试类实现与其测试类相同的接口。这样,当接口发生变化时(我们正处于早期开发阶段,它会发生变化),编译器可以保证将相应的方法添加到测试类中。例如:
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
}
}
当我尝试这样做时,我收到错误:“java.lang.Exception:方法 getFoo() 应该为 void”, 大概是因为测试方法必须返回 void。有人知道有什么办法解决这个问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我必须承认,这是一个巧妙的技巧,尽管它不能很好地扩展到多个测试场景。
无论如何,您可以使用自定义跑步者。例如:
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:
更自然的方法可能是使用代码覆盖率工具,例如 Cobertura。它与 JUnit 很好地集成,并且它向您展示了您的测试在某些情况下可能存在缺陷的情况(尽管有很多情况这样的工具无法捕获)。
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).