John Oxley
John Oxley

Reputation: 15010

Spring Mockito TestNG - Mocks persist across tests

Given the following members of my test class

@Mock
private Gateway gateway;
@Autowired
@InjectMocks
private TransactionManager transactionManager;

@BeforeClass
public void before() {
    MockitoAnnotations.initMocks(this);
}

The TransactionManager uses the gateway internally and it is wired up with @Autowired. When I run the tests in this class, they pass. However when I run tests in a separate class that I am expecting to use the concrete implementation of Gateway, they are using the mocked Gateway.

Upvotes: 2

Views: 2095

Answers (2)

mrboo
mrboo

Reputation: 76

I had the same Problem. You can use @DirtiesContext on the test class.

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html

In this case you don't need any extra packages or code. The context will be reinitialized after your test.

Upvotes: 0

Marcin Grzejszczak
Marcin Grzejszczak

Reputation: 11189

You have to check out the Mockito's subproject for TestNG. You can see an example of usage here in my Mockito Cookbook repo - https://github.com/marcingrzejszczak/mockito-cookbook/blob/master/chapter01/src/test/java/com/blogspot/toomuchcoding/book/chapter1/_3_MockitoAnnotationsTestNg/assertj/MeanTaxFactorCalculatorTestNgTest.java.

To use the listener you have to copy the contents of the https://github.com/mockito/mockito/tree/master/subprojects/testng/src/main/java/org/mockito/testng folder to your project since mockito-testng is not yet released.

Upvotes: 3

Related Questions