【问题标题】:How to Mock deleteById using mockito in spring boot如何在 Spring Boot 中使用 mockito 模拟 deleteById
【发布时间】:2019-12-03 11:58:13
【问题描述】:

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

【问题讨论】:

标签: spring spring-boot mockito junit4


【解决方案1】:

这取决于你想在哪里使用这个模拟。对于使用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 runner 和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 方法返回 void,因此添加模拟注释并检查是否调用了模拟方法(如果需要)应该足够了。

您可以找到更多信息here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多