How and when to cleanup using Mockito Annotations with jUnit
garbage-collection, java, junit, mockito, unit-testing
Solution
JUnit creates a new instance of your unit test class before running each test method. Once the instance is created, its `@Before` annotated method(s) is (are) executed. Then the test method is executed. Then, whatever happened in the test method (success, failure or error), the @After annotated method(s) is (are) run.
So, in this particular case, `MockitoAnnotations.initMocks(this)` is executed before each test method, which creates a new mock each time, a new MyBeanToTest each time, and injects the mock into the bean to test.
Those beans will be eligible for GC, along with the test instance which references them, after the test method execution. Setting them to null in the cleanup method doesn't serve any purpose.
Problem
I'm currently having some memory problems with some unit tests in a fairly large project of mine. Throughout my hair pulling and research today, I have come to realize that it appears to be related to objects not always being cleaned up as fast as I think they should be cleaned up. I started researching "cleanup mockito" and "cleanup junit" and came across a few blogs and forum posts about how to use `@Before` and `@After` (as well as their *Class versions) to do intense things that you don't want being done with every unit test. This got me to thinking about Mockito's `@Mock` and `@InjectMocks` annotations. Can someone please describe to me in detail how the class variables below are being handled in memory during a maven build? Will the objects be created before, during, or after unit tests? Are the objects immediately destroyed after the last unit tests completes? Should I be using `@After` to set all the class variables to null? Thanks many times over. Here's a sample of a test case I may use: ``` @RunWith(MockitoJUnitRunner.class) public class thisCustomTest { @Mock MyCustomSpringBean myCustomerSpringBean; @InjectMocks MyBeanToTest myBeanToTest; @Before public void config() { MockitoAnnotations.initMocks(this); } @Test public void someTest() { //code here } } ``` Just to do a quick wrap-up / summary at the end, my main question is whether or not I should be utilizing something like `@After` to clean up class variables, or should I simply leave those for Java's normal scope garbage collection... My idea of cleanup: ``` @After public void cleanup() { mockedClassVariable = null; injectedVariable = null; } ```