When writing unit tests, I always extends Assert
, so I have unqualified access to the many calls to the many Assert.assertXXX
methods:
For example:
public class MyTestClass extends Assert {
@Test
public void SomeTest() {
assertNotNull(""); // instead of Assert.assertNotNull("");
}
}
Extending Assert
saves me typing Assert.assertNotNull("");
. The Assert.
clutters up the code in my opinion, because you use it a lot.
My test classes rarely need to extend another class, and if they do I tend to make the superclass extend Assert.
However, it feels like I'm breaking some coding style to extend just to avoid importing and qualifying.
It this "poor" coding style?
Is it is still "best practice" code if I do this, because it's only a test class?
import static org.junit.Assert.*;
Doesn't work because have my Eclipse code formatter resolve all imports, so such a line gets zapped and replaced with individual imports for all methods actually used every time I save, leaving me to re-import if I use a new assert method.
Admittedly, after a while of coding a test class the need to import new methods reduces, but when coding a new test class it's a hassle.
No, do it like this:
import static org.junit.Assert.*;
public class MyTestClass {
@Test
public void SomeTest() {
assertNotNull("");
}
}
Personally I don't like extending classes if I don't need to. Have you considered using static import of the Methods you're using? On a side note I'd recommend trying Fest assertions for nicer, more readable tests.
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