简体   繁体   中英

How to Mock deleteById using mockito in spring boot

如何在 Spring Boot 中使用 mockito 模拟mockRepository.deleteById()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM