我需要使用lambda Consumer测试使用另一个接口作为依赖项注入的calss.
@Builder
public class Interactor {
private final Gateway gateway;
void process(String message, Consumer<String> response){
gateway.process(message, uuid -> {
response.accept(uuid.toString());
});
}
}
依赖关系的定义如下:
public interface Gateway {
void process(String message, Consumer<UUID> uuid);
}
我将如何模拟网关,以便为测试提供UUID值响应?
这是我到目前为止尝试过的:
@Test
void whillReturnTheInjectedUUIDValueTest() {
UUID uuid = UUID.randomUUID();
Gateway gateway = Mockito.mock(Gateway.class);
Mockito.when(gateway.process("ignored", uuid1 -> {return uuid;}));
Interactor.builder().gateway(gateway).build().process("ignored", s -> {
Assertions.assertEquals(uuid.toString(), s);
});
}
我应该如何向消费者提供退货价值?
解决方法:
现在,我最终在没有Mockito的情况下嘲笑了自己的内部类.
class InteractorTest {
@Test
void whillReturnTheInjectedUUIDValueTest() {
UUID uuid = UUID.randomUUID();
Gateway gateway = GatewayMock.builder().value(uuid).build();
Interactor.builder().gateway(gateway).build().process("ignored", s -> {
Assertions.assertEquals(uuid.toString(), s);
});
}
@Builder
private static class GatewayMock implements Gateway {
private final UUID value;
@Override
public void process(String message, Consumer<UUID> uuid) {
uuid.accept(value);
}
}
}