Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting Mockito mocks, provided as Spring beans, between tests?

Tags:

spring

mockito

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.

like image 478
Philip Avatar asked Jan 21 '16 21:01

Philip


1 Answers

I had to add this at the start:

@BeforeEach
void setup() {
     Mockito.reset(...mockBeans);
     ...
}
like image 126
Enrico Graziani Avatar answered Nov 11 '22 20:11

Enrico Graziani