HAR*_*ISH 3 spring junit4 mockito spring-boot
如何在Spring Boot中使用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
}
}
Run Code Online (Sandbox Code Playgroud)
对于单元测试,您可以使用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
}
}
Run Code Online (Sandbox Code Playgroud)
该deleteById方法返回 void,因此添加模拟注释并检查是否调用了模拟方法(如果需要)就足够了。
您可以在这里找到更多信息
| 归档时间: |
|
| 查看次数: |
5586 次 |
| 最近记录: |