[英]Verify BiConsumer as method reference in Unit Test
I have some logic quite similar to this, where i have unit and different fields that can be updated during request.我有一些与此非常相似的逻辑,其中我有可以在请求期间更新的单元和不同的字段。
public class Unit {
int x;
int y;
public void updateX(int x) {
this.x += x;
}
public void updateY(int y) {
this.y += y;
}
}
public class UpdateUnitService{
public Unit update(int delta, BiConsumer<Unit, Integer> updater){
Unit unit = getUnit(); //method that can`t be mocked
updater.accept(unit, delta);
// some save logic
return unit;
}
}
public class ActionHandler{
private UpdateUnitService service;
public Unit update(Request request){
if (request.someFlag()){
return service.update(request.data, Unit::updateX);
}else {
return service.update(request.data, Unit::updateY);
}
}
}
And I need write some test for checking what function was called.我需要编写一些测试来检查调用了什么函数。 Something like this.像这样的东西。
verify(service).update(10, Unit::updateX);
verify(service).update(10, Unit::updateY);
How to write test like this using ArgumentCaptor or something else?如何使用 ArgumentCaptor 或其他方式编写这样的测试?
There is no way (in current implementation of Java) to compare two lambdas and/or method references.没有办法(在 Java 的当前实现中)比较两个 lambda 和/或方法引用。 For more details read this post .有关更多详细信息,请阅读这篇文章。
What you could do (in case getUnit()
is unmockable) is to check whether the two method references do the same thing when invoked.您可以做的是(如果getUnit()
不可模拟)是检查两个方法引用在调用时是否执行相同的操作。 But you can't verify any unknown side effects.但是您无法验证任何未知的副作用。
public void verifyUpdateTheSameField(Integer value, BiConsumer<Unit, Integer> updater1, BiConsumer<Unit, Integer> updater2) {
Unit unit1 = // initialize a unit
Unit unit2 = // initialize to be equal to unit1
actual.accept(unit1, value);
expected.accept(unit2, value);
assertThat(unit1).isEqualTo(unit2);
}
And then:进而:
ArgumentCaptor<Integer> valueCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<BiConsumer<Unit, Integer>> updaterCaptor = ArgumentCaptor.forClass(BiConsumer.class);
verify(handler.service, times(1)).update(valueCaptor.capture(), updaterCaptor.capture());
verifyUpdateTheSameFields(valueCaptor.getValue(), updaterCaptor.getValue(), Unit::updateX);
Note: This approach will work only if Unit
overrides equals
.注意:此方法仅在Unit
覆盖equals
时才有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.