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

时间:2016-08-18 11:57:09

标签: unit-testing mockito functional-interface

我正在尝试对在Consumer功能界面中作为回调运行的代码进行单元测试。

@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”为测试代码提供一些经过测试的“消息”。

如何模拟“toBeMockedDependency”以提供预定义的消息? 这是正确的做法吗?

1 个答案:

答案 0 :(得分:3)

请勿尝试让toBeMockedDependency自动调用您的功能界面。而是使用@Captor capture匿名功能界面,然后使用您的测试手动调用它。

@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(...);
  }
}