如何在 spring 引导中使用 mockito 模拟 deleteById

How to Mock deleteById using mockito in spring boot

如何在 spring 引导中使用 mockito 模拟 mockRepository.deleteById()

这取决于你想在哪里使用这个模拟。对于集成测试 运行 SpringRunner 可以使用 MockBean 注释注释要模拟的存储库。这个模拟 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
    }
}

对于单元测试,您可以使用 MockitoJUnitRunner 运行程序和 Mock 注释:

@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
    }
}

deleteById 方法 returns void,所以添加模拟注释并检查是否调用了模拟方法(如果需要)就足够了。

您可以找到更多信息here