簡體   English   中英

對該方法進行單元測試的最佳方法?

[英]Best way to unit test this method?

我有以下 class

public class Multiplier {
    private static Map<Integer, Float> map;
    private static final float DEFAULT_MULTIPLIER = 4.4F;

    static {
        // This map is actually populated by reading from a file. This is an example on how the map looks like.
        map = new HashMap<>();
        map.put(1, "3.5F");
        map.put(2, "5.8F");
        map.put(3, "2.7F");
    }

    public static float getMultiplier(Integer id) {
        return map.getOrDefault(id, DEFAULT_MULTIPLIER);
    }
}

我還有一個 class

public class MultiplierUser {
    private integer id;
    private float value;
    private float result;

    public MultiplierUser(int id, float value) {
        this.id = id;
        this.value = value;
    }

    public void setResult() {
        result = value * Multiplier.getMultiplier(this.id);
    }

    public float getResult() {
        return this.result;
    }
}

測試此方法的最佳方法是什么?

我應該通過調用方法然后斷言來獲得預期值嗎?

public testMethod() {
    MultiplierUser multiplierUser = new MultiplierUser(1, 10F);
    multiplierUser.setResult();
    
    float expected = Multiplier.getMultiplier(1) * 10F;

    Assert.assertEquals(expected, multiplierUser.getResult());
}

還是嘲笑?

public testMethod() {
    MultiplierUser multiplierUser = new MultiplierUser(1, 10F);

    Mockito.mock(Multiplier.class);
    when(mock.getMultiplier(1)).thenReturn(1.5F);

    multiplierUser.setResult();

    float expected = 1.5F * 10F;
    Assert.assertEquals(expected, multiplierUser.getResult());
}

我不明白哪個是測試此方法的更好方法? 如果我使用前者,我基本上是自己調用方法並獲得結果。 但是,如果將來該方法出現問題,測試將繼續成功。 如果我使用的是模擬,那么從技術上講,我並沒有測試該方法及其返回的值。 我糊塗了。 請幫忙。

要測試setResult方法,mocking Multiplier就足夠了。

在這種情況下,方法setResultgetMultiplier非常簡單。

但是讓我們考慮一個涉及復雜操作的場景:

public class A {
    public int foo1() {
        //some complex operations
    }
}
public class B {
    public int foo2() {
        A a = new A();
        int val = a.foo1();
        //some complex operations
    }
}

現在要測試foo2() ,模擬class A並使用thenReturn獲取一些樣本 output 比在foo2()測試中測試整個foo1()方法更有意義。 這確保您只測試與被測方法相關的相應代碼單元。

單元測試的設計應使其簡單、可讀並一次處理一個邏輯。

暫無
暫無

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

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