Thursday, December 19, 2013

JUnit Testing Tips - Constructor is Called Before Executing Test Methods

Most of Java programmers either use JUnit or TestNG for there unit testing need, along with some mock object generation libraries e.g. Mockito, but not everyone spend time and effort to learn subtle details of these testing libraries, at least not in proportion of any popular framework e.g. Spring or Hibernate. In this blog post, I am sharing one of such details, which has puzzled me couple of years ago. At that time, though I had been using JUnit for significant time, I wasn't aware that code written inside constructor of Test class is executed before each test method. This behaviour of JUnit has caused, some of my test to failed and putting hours of investigation in my code, without realizing that this is happening because of JUnit is initializing object by calling constructor before executing test method annotated with @Test annotation. I had following code to test my vending machine implementation as coding exercise. If you look at closely, I have initialized vending machine in class body, which is executed as part of constructor. I was assuming one instance of vending machine is shared between all test methods, as I was not using @Before and @After, JUnit 4 annotation for setup() and tearDown(). In first test, one item from Inventory is consumed and in second test another item, but when you assert count of items based upon previous test, it will fail, because you are testing a different vending machine instance, which has different inventory. So always, remember that JUnit calls constructor of test class before executing test method. You can verify it by putting a System.out.println message in constructor itself.
Read more �

No comments:

Post a Comment