【发布时间】:2019-11-13 13:20:20
【问题描述】:
是否可以测试用 lambda 函数编写并在方法 process 内部传递的代码?
@AllArgsConstructor
public class JsonController {
private final JsonElementProcessingService jsonElementProcessingService;
private final JsonObjectProcessingService jsonObjectProcessingService;
private final JsonArrayProcessingService jsonArrayProcessingService;
public void process(String rawJson) {
jsonElementProcessingService.process(json -> {
JsonElement element = new JsonParser().parse(json);
if (element.isJsonArray()) {
return jsonArrayProcessingService.process(element.getAsJsonArray());
} else {
return jsonObjectProcessingService.process(element.getAsJsonObject());
}
}, rawJson);
}
}
由于 lambda 是惰性的,所以当我调用 JsonController::process 时,不会调用函数 (Function::apply) 所以有什么方法可以检查 jsonArrayProcessingService::process 是否被调用?
@RunWith(JMockit.class)
public class JsonControllerTest {
@Injectable
private JsonElementProcessingService jsonElementProcessingService;
@Injectable
private JsonObjectProcessingService jsonObjectProcessingService;
@Injectable
private JsonArrayProcessingService jsonArrayProcessingService;
@Tested
private JsonController jsonController;
@Test
public void test() {
jsonController.process("[{\"key\":1}]");
// how check here that jsonArrayProcessingService was invoked?
}
}
【问题讨论】:
-
我不熟悉
jmockit,但我认为在您的情况下正确的步骤是:“运行 UUT 方法,从模拟依赖项中获取注入的 lambda,运行它,验证,基于你传递的 json,正确的模拟被调用。”主要原因是您必须首先验证调用了正确的JsonElementProcessingService方法,然后通过调用它传递的 lambda 执行正确的细化。