dhblah
dhblah

Reputation: 10151

Using mockito is there a reason to nullify mocks in @After?

I'm wondering,

If in @Before method I'm initializing a mock objects, shouldn't I nullify references to it in @After ? Or would that be redundant? And why?

Upvotes: 2

Views: 161

Answers (2)

makasprzak
makasprzak

Reputation: 5220

"Nullifying" reference doesn't change anything here.

@Before annotated method is ran before each test method. If you are initializing mocks in such method they will be reinitialized before each test. There is a different annotation - @BeforeClass, this annotation causes a method to be executed only once before execution of any test method in that test class. In this case however "nullifying" a reference will not help you because you still need to create a new mock object and assign its reference to your field.

Upvotes: 0

bric3
bric3

Reputation: 42283

Not necessary, JUnit creates a new instance of the test per test method.

However if it's static fields it's another story, and proper lifecycle should be implemented, but I strongly advise you to not use static fields in a JUnit test ! Instead think about implementing your own JUnit Runner.

And for TestNG, it's a different story, as TestNG creates a single instance of the test, so you have to be careful there on the lifecycle of the mocks.

Upvotes: 6

Related Questions