为了账号安全,请及时绑定邮箱和手机立即绑定

如何多次模拟具有不同参数的一种方法?

如何多次模拟具有不同参数的一种方法?

慕丝7291255 2023-08-04 16:44:33
我有一些测试方法:@Testpublic void test_method() {    MyObj mock = mock(MyObj.class);    when(mock.get("testName", "1")).thenReturn("Result1");    when(mock.get("test", "2")).thenReturn("rrrr");}当我尝试运行这个方法时,我遇到了异常:org.mockito.exceptions.misusing.PotentialStubbingProblem: Strict stubbing argument mismatch. Please check:Typically, stubbing argument mismatch indicates user mistake when writing tests.Mockito fails early so that you can debug potential problem easily.However, there are legit scenarios when this exception generates false negative signal:  - stubbing the same method multiple times using 'given().will()' or 'when().then()' API    Please use 'will().given()' or 'doReturn().when()' API for stubbing.  - stubbed method is intentionally invoked with different arguments by code under test    Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).For more information see javadoc for PotentialStubbingProblem class.我如何模拟这个方法?
查看完整描述

3 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

错误消息告诉您:

'given().will()'使用或API多次存根同一方法'when().then()'请使用'will().given()''doReturn().when()'API 进行存根。


查看完整回答
反对 回复 2023-08-04
?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

您可以使用any()来模拟具有不同参数的一种方法。any() 将用作动态变量。


例如 doReturn(order).when(orderRepository).save(any(Order.class));


我使用 2 个不同的 Order 参数保存 orderRepository,因此我将任何一个与 Order 类一起使用。


查看完整回答
反对 回复 2023-08-04
?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

对我来说,添加注释 @MockitoSettings(strictness = Strictness.LENIENT)

@ExtendWith(MockitoExtension::class)
@MockitoSettings(strictness = Strictness.LENIENT)


查看完整回答
反对 回复 2023-08-04
  • 3 回答
  • 0 关注
  • 171 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信