简体   繁体   English

如何在 Spring Boot 中使用 mockito 模拟 deleteById

[英]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.对于使用SpringRunner运行的集成测试,可以使用MockBean注释来注释存储库以模拟。 This mocked bean will be automatically inserted in your context:这个模拟 bean 将自动插入到您的上下文中:

@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:对于单元测试,您可以使用MockitoJUnitRunnerMock注释:

@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). deleteById方法返回 void,因此添加模拟注释并检查是否调用了模拟方法(如果需要)应该就足够了。

You can find more info here你可以在这里找到更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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