I am attempting to test the default constructor for a class, using Junit:
// testing default const
public void testCaesarCipher() {
CaesarCipher c1 = new CaesarCipher();
if (c1 == null) {
assertTrue(false);
} else {
assertTrue(true);
}
}
I am getting the error of "Dead code", how do I fix this?
Get rid of the check for c1
being null - that's provably impossible. A constructor can never return null
.
You may want to test that your constructor doesn't throw an exception - in which case just:
public void testCaesarCipher() {
new CaesarCipher();
}
... is fine. The fact that the constructor returns without throwing an exception is all that the test will prove though, at execution time. (The presence of the test is a compile-time check that there's a parameterless constructor, of course.)
I expect your other tests will need to call the constructor anyway though, in which case do you really think it's worth having this test at all?
Additionally, if you really did want to check that some value wasn't null, you should use:
assertNotNull(c1);
That's much clearer than your if
/else
. And in cases where you want to programmatically fail, just call fail()
rather than assertTrue(false);
.
See more on this question at Stackoverflow