模拟; 模拟调用 lambda 的方法,并验证该 lambda 调用的另一个模拟

我仍然需要一段时间才能弄清楚:


如何验证在传递给另一个模拟对象的方法的 lambda 中使用的模拟调用的方法?


这可能看起来很复杂,但在 Java 8 库(如 JDBI)中经常发生这种情况,例如,您有一个 JDBI 对象:


JDBI MyDBConnection

你应该嘲笑。然后将其与 withHandle 方法一起使用以传递实现 HandleCallback<R,X> 类型的 lambda:


//code I'm testing. I implement the lambda, and want to verify it

//calls the correct method in dao provided by JDBI.

MyDBConnection.withHandle(

    (handle) -> { ... handle.attach(SomeDao.class).findSomethingInDB(args) .. }

这是推荐的方法。


所以我想验证是否调用了 findSomethingInDB(eq(args))。


就像我说的那样,这很相似,但又足够不同,至少,当我忘记如何做到这一点时,我至少会发现这个答案很有价值。因此,调用我的 lambda 的原始 3rd 方库方法的处理类似于上面引用的问题中给出的答案,但有一些调整:


when(JDBIMock.withHandle(any())).then(

  //Answer<Void> lambda

  invocationOnMock -> {

     Object[] args = invocationOnMock.getArguments();

     assertEquals(1, args.length);

     //the interface def for the callback passed to JDBI

     HandleCallback lambda = (HandleCallback) args[0];

     when(mockHandle.attach(SomeDao.class)).thenReturn(mockDao);

     //this actually invokes my lambda, which implements the JDBI interface, with a mock argument

     lambda.withHandle(mockHandle);

     //bingo!

     verify(mockDao).findSomethingInDB(eq(args));

  }

)


鸿蒙传说
浏览 137回答 2
2回答

桃花长相依

我正在尝试做一些非常类似的事情,以验证从withHandle测试中的模拟 JDBI 调用传递给另一个模拟的参数。您在问题中给出的答案为我指明了正确的方向,但给了我错误消息:The method then(Answer<?>) in the type OngoingStubbing<Object> is not applicable for the arguments ((<no type> invocationOnMock) -> {})相反,我不得不使用新的org.mockito.stubbing.Answer传递给then,类似于您链接到的另一个问题。在您的示例中,这将类似于:when(JDBIMock.withHandle(any())).then(&nbsp; //Answer<Void> lambda&nbsp; new Answer<Void>() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public Void answer(InvocationOnMock invocation) throws Throwable {&nbsp; &nbsp; &nbsp; Object[] args = invocation.getArguments();&nbsp; &nbsp; &nbsp; assertEquals(1, args.length);&nbsp; &nbsp; &nbsp; //the interface def for the callback passed to JDBI&nbsp; &nbsp; &nbsp; HandleCallback lambda = (HandleCallback) args[0];&nbsp; &nbsp; &nbsp; when(mockHandle.attach(SomeDao.class)).thenReturn(mockDao);&nbsp; &nbsp; &nbsp; //this actually invokes my lambda, which implements the JDBI interface, with a mock argument&nbsp; &nbsp; &nbsp; lambda.withHandle(mockHandle);&nbsp; &nbsp; &nbsp; //bingo!&nbsp; &nbsp; &nbsp; verify(mockDao).findSomethingInDB(eq(args));&nbsp; &nbsp; &nbsp; return null; // to match the Void type&nbsp; &nbsp; }&nbsp; })在我的情况下,我期待一个结果列表,withHandle所以我不得不更改Answer类型,并返回类型answer以匹配并返回一个虚拟列表而不是Void. (在这个测试中返回的实际结果并不重要,只是将预期的参数传递给我随后的模拟对象)。我还将verify调用移到了Answer测试的主体中,因此更清楚的是这是测试的预期,而不是模拟设置的一部分。

开心每一天1111

看到这个问题,上面应该充分回答;)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java