我想问一下你是否有任何技术可以用单元测试覆盖try-with-resource。我用它打开一些流,eclemma告诉我,我已经在这个try-with-resource块上发现了分支。据我所知,这个块在编译后显然被翻译成了其他东西,但这是否意味着如果我使用它,我不能100%覆盖emma? 你有什么技术可以解决这个问题吗?我100%喜欢我的报道。
谢谢!
答案 0 :(得分:9)
简短的回答是否定的。
答案很长: 如下所述:8 branches for try with resources - jacoco coverage possible? try-with-resource被编译成一组非常复杂的语句,其中某些分支可能无法被每个人的代码访问。
截至目前(2014年10月)Jacoco(eclemma)没有为您过滤那些无法访问的分支,但有ticket要做,但我不知道它是否或何时实施。
虽然100%的代码覆盖率很好,但盲目跟进并不是一个好的指标。除了执行所有代码行的测试之外,100%代码覆盖率不会告诉您任何其他内容。如果覆盖的代码做错了或者做得不够,你的代码仍然可能有bug。 多年来,我发现在100%覆盖的代码区域中存在许多错误,因为虽然我的测试覆盖了所有语句,但我没有考虑所有边缘情况,所以我的代码在极少数情况下表现不正确。
此外,如果你的项目足够大,这些错过的分支几乎没有什么区别。那么如果你只有99%的覆盖率呢。
答案 1 :(得分:1)
我这样做了:
public class Something implements AutoCloseable {
private HttpAutomationClient client;
//methods for connecting, etc
@Override
public void close() {
shutdown();
}
void shutdown() {
client.shutdown();
}
}
public class SomethingTest {
//stuff
@Test
public autocloseableShutsDownTheClient() {
final HttpAutomationClient client = mock(HttpAutomationClient.class);
Something something = null;
try (final Something spy = spy(new Something())) {
something = spy;
TestHelper.setField(something, "client", client); //sets a field using reflection
}
verify(somehing).shutdown();
verify(client).shutdown();
}
}
答案 2 :(得分:0)
在编写测试用例时,实际上我们应该关注功能而不是测试覆盖率。如果你想覆盖这些区域,最好使用一些模拟工具,如jmockit来覆盖那些尝试区域