5

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

@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”以提供预定义的消息?
这是正确的方法吗?

4

1 回答 1

8

不要试图toBeMockedDependency自动调用你的功能接口。相反,使用 a@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(...);
  }
}
于 2016-08-18T17:46:03.647 回答