6
votes

I have a Java application that uses Spring's dependency injection. I want to mock out a bean, and verify that it receives certain method calls.

The problem is that Mockito does not reset the mock between tests, so I cannot correctly verify method calls on it.

My unit under test:

public class MyClass {
  @Resource
  SomeClientClass client;

  public void myMethod() {
    client.someMethod();
  }
}

The unit test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = UnitTestConfig.class)
public class MyClassTest {
  @Resource
  SomeClientClass client;

  @Test
  public void verifySomething() {
    // ...
    Mockito.verify(client).publish();
  }
}

Finally,

@Configuration
public class UnitTestConfig {
  @Bean
  SomeClientClass client() {
    return Mockito.mock(SomeClientClass.class);
  }
}

Though I could hack my way around this problem by manually resetting mocks between tests, I wonder if there's a cleaner / more idiomatic approach.

1
Try using @DirtiesContext with your test classjny
Did you end up finding a way?jmrah

1 Answers

3
votes

I had to add this at the start:

@BeforeEach
void setup() {
     Mockito.reset(...mockBeans);
     ...
}