基于消费者功能接口的单元测试回调



我正在尝试单元测试在消费者功能接口中作为回调运行的代码。

@Component
class SomeClass {
  @Autowired
  private SomeInteface toBeMockedDependency;
  public method() {
     toBeMockedDependency.doSomething(message -> {
        // Logic under test goes here 
        //             (implements java.util.function.Consumer interface)
        ...
     });
  }
}
@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest {
  @InjectMocks
  private SomeClass someClass;
  @Mock
  private SomeInteface toBeMockedDependency;
  @Test
  public void testMethod() {
    ...
    someClass.method();
    ...
  }
}

本质上,我想通过"toBeMockedDependency"为测试代码提供一些经过测试的"message"。

如何模拟"toBeMockedDependency"来提供预定义的消息?
这是正确的方法吗?

不要试图让toBeMockedDependency自动调用你的功能接口。相反,使用@Captor捕获匿名功能接口,然后使用您的测试手动调用它。

@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest {
  @InjectMocks
  private SomeClass someClass;
  @Mock
  private SomeInteface toBeMockedDependency;
  @Captor
  private ArgumentCaptor<Consumer<Message>> messageConsumerCaptor;
  @Test
  public void testMethod() {
    someClass.method();
    verify(toBeMockedDependency).doSomething(messageConsumerCaptor.capture());
    Consumer<Message> messageConsumer = messageConsumerCaptor.getValue();
    // Now you have your message consumer, so you can test it all you want.
    messageConsumer.accept(new Message(...));
    assertEquals(...);
  }
}

相关内容

  • 没有找到相关文章

最新更新