gpt4 book ai didi

spring - 如何在 spring boot 中使用 mockito 模拟 deleteById

转载 作者:行者123 更新时间:2023-12-05 02:10:10 24 4
gpt4 key购买 nike

如何在 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
}
}

对于单元测试,您可以使用 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 方法返回 void,因此添加模拟注释并检查是否调用了模拟方法(如果需要)就足够了。

您可以找到更多信息 here

关于spring - 如何在 spring boot 中使用 mockito 模拟 deleteById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59156602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com