【发布时间】:2019-12-03 11:58:13
【问题描述】:
如何在 Spring Boot 中使用 mockito 模拟 mockRepository.deleteById()?
【问题讨论】:
-
这能回答你的问题吗? JUnit for void delete method
标签: spring spring-boot mockito junit4
如何在 Spring Boot 中使用 mockito 模拟 mockRepository.deleteById()?
【问题讨论】:
标签: spring spring-boot mockito junit4
这取决于你想在哪里使用这个模拟。对于使用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
【讨论】: