2014-02-09

JUnit lifecycle

Introduction

JUnit is basic and first tool which is used for testing in Java. JUnit uses annotations to describe lifecycle, but sometimes order of operations executed by this library is not obvious. For example: when constructor of test class is called or when static initalization block is executed?

Main

This JUnit test class will be used to show when methods and blocks are executed.

Before each test not only method annotated with Before is called. Earlier initialization block and constructor is called. There you can create resources, which should be not shared between tests (for example to get HibernateSession from SessionFactory).

Conclusion

It is why JUnit is great for unit testing. State for each test could be created in initial block, constructor of before method and it does not share it between test methods, because for each test new class is created. Of course, You can always store something in static variables, for example heavy objects which You want to create only once.