Annotations in Java

I am working on a new project using Java, Jersey, MongoDB with MongoJack, JUnit and maven.

As MongoDB is pretty fast the need of mockers can be avoided in tests. but the database needs to have the data.

In my case, there is a test just for that: it creates and saves all the data needed. The problems is that it has to be run before the other tests !

Instead of finding a way to give the tests an order, I just created a base class that all the testing classes extends and put a method with the annotation @Before. That method initialized all the necesary things (in my case MongoDB) and ran all the methods with @Test annontation in the class in charge of loading the data.

public abstract class BaseTest {

    @Before
    public void startMongoConnection() throws UnknownHostException, InvocationTargetException, IllegalAccessException {
        if (!MongoConnection.isActive()) {
            EntitySavingTest entitySavingTest = new EntitySavingTest();
            MongoConnection.initializeForDevelopment();
            for (Method method : entitySavingTest.getClass().getMethods()) {
                if(method.isAnnotationPresent(Test.class)) {
                    method.invoke(entitySavingTest);
                }
            }
            extraSetup();
        }
    }

    protected void extraSetup() {
    }

}

public class ATest extends BaseTest {

    @Override
    public void extraSetup() {
        //Any extra things you need to have before the test starts
    }

    @Test
    public void test() {
        //Testing code...
    }

}

Pretty simple and useful !

I got all the information about annotations here:

http://www.vogella.com/articles/JavaAnnotations/article.html

Advertisements