是否可以测试在方法 process
中传递的用 lambda 函数编写的代码?
@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?
}
}
最佳答案
只需将其转换为方法使其可测试(和可读)即可:
public void process(String rawJson) {
jsonElementProcessingService.process(this::parse, rawJson);
}
Object parse(String json) {
JsonElement element = new JsonParser().parse(json);
if (element.isJsonArray()) {
return jsonArrayProcessingService.process(element.getAsJsonArray());
} else {
return jsonObjectProcessingService.process(element.getAsJsonObject());
}
}
我个人遵循的相关指导原则是:
- 每当我的 lambda 需要花括号时,将它们转换为方法
- 组织代码使其可以进行单元测试
您可能需要更改 parse
方法的返回类型以匹配您的处理服务(您未显示)返回的任何内容。
关于java - 当函数的代码作为方法参数传递时,如何测试它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58838072/