簡體   English   中英

驗證 BiConsumer 作為單元測試中的方法參考

[英]Verify BiConsumer as method reference in Unit Test

我有一些與此非常相似的邏輯,其中我有可以在請求期間更新的單元和不同的字段。

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);
        }
    }
}

我需要編寫一些測試來檢查調用了什么函數。 像這樣的東西。

verify(service).update(10, Unit::updateX);
verify(service).update(10, 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);
}

進而:

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);

注意:此方法僅在Unit覆蓋equals時才有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM