Java 验证双消费者作为单元测试中的方法参考

Java 验证双消费者作为单元测试中的方法参考,java,java-8,mockito,powermock,method-reference,Java,Java 8,Mockito,Powermock,Method Reference,我有一些与此非常相似的逻辑,其中我有可以在请求期间更新的单元和不同字段 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

我有一些与此非常相似的逻辑,其中我有可以在请求期间更新的单元和不同字段

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);
        }
    }
}
如何使用ArgumentCaptor或其他工具编写这样的测试?

在当前的Java实现中,无法比较两个lambda和/或方法引用。欲了解更多详情,请阅读

您可以做的(如果
getUnit()
不可修改)是检查两个方法引用在调用时是否做相同的事情。但你无法证实任何未知的副作用

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);
}
public void verifyUpdateTheSameField(整数值、双消费者更新程序1、双消费者更新程序2){
unit1=//初始化一个单元
unit2=//初始化为等于unit1
实际接受(单位1,价值);
预期。接受(单元2,值);
资产(单位1)。isEqualTo(单位2);
}
然后:

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);
ArgumentCaptor valueCaptor=ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor updaterCaptor=ArgumentCaptor.forClass(BiConsumer.class);
验证(handler.service,times(1)).update(valueCaptor.capture(),updaterCaptor.capture());
验证UpdateTheSameFields(valueCaptor.getValue()、updaterCaptor.getValue()、Unit::updateX);

注意:只有当
单元
覆盖
等于
时,此方法才有效

您应该测试操作是否正确,即
单元
之后是否包含正确的值。它是如何做到的,例如通过方法引用调用特定的方法,是不相关的。
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);