Reputation: 211
How to Mock mockRepository.deleteById() using mockito in spring boot?
Upvotes: 3
Views: 6044
Reputation: 4202
It depends on where you want to use this mock. For integration tests running with the SpringRunner
it is possible to annotate the repository to mock with the MockBean
annotation. This mocked bean will be automatically inserted in your context:
@RunWith(SpringRunner.class)
public class SampleIT {
@MockBean
SampleRepository mockRepository;
@Test
public void test() {
// ... execute test logic
// Then
verify(mockRepository).deleteById(any()); // check that the method was called
}
}
For unit tests you can use the MockitoJUnitRunner
runner and the Mock
annotation:
@RunWith(MockitoJUnitRunner.class)
public class SampleTest {
@Mock
SampleRepository mockRepository;
@Test
public void test() {
// ... execute the test logic
// Then
verify(mockRepository).deleteById(any()); // check that the method was called
}
}
The deleteById
method returns void, so it should be enough to add the mock annotation and check if the mocked method was called (if needed).
You can find more info here
Upvotes: 5