Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test class style [closed]

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?

Edit:

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.

like image 971
Bohemian Avatar asked Dec 21 '22 11:12

Bohemian


2 Answers

No, do it like this:

import static org.junit.Assert.*;

public class MyTestClass {
   @Test
   public void SomeTest() {
       assertNotNull("");
   }
}
like image 106
asgoth Avatar answered Dec 30 '22 01:12

asgoth


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.

like image 41
Peter Svensson Avatar answered Dec 30 '22 02:12

Peter Svensson