I wanted to ask if you have any techniques for covering try-with-resource with unit tests. I'm using it to open some stream and eclemma is showing me that I have uncovered branches on this try-with-resource block. I understand that this block is apparently translated into something else after compilation, but does that mean that I can't have 100% coverage with emma if I use this? Do you have any techniques to handle this issue? I like my coverage 100%.
Thanks!
The short answer is no.
Long answer: As described here: 8 branches for try with resources - jacoco coverage possible? a try-with-resource gets compiled into a very complicated group of statements where some branches are probably not reachable by everyone's code.
As of now (Oct 2014) Jacoco (eclemma) does not filter those unreachable branches for you however there is a ticket to do that but I don't know if it or when it will ever be implemented.
While 100% code coverage is nice, it's not a good metric to blindly follow. 100% code coverage doesn't tell you anything other than you have tests that execute all your lines of code. Your code can still have bugs if that covered code does the wrong thing or doesn't do enough. Over the years, I've found many bugs in regions of code that were 100% covered because while I had tests that covered all the statements, I didn't consider all the edge cases so my code behaved incorrectly on rare occasions.
Also, if your project is large enough, these missed branches will hardly make a difference. So what if you only have 99% coverage.
I did this:
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With