簡體   English   中英

JUnit 測試除法()方法的正確方法

[英]Correct way to JUnit test divide() method

我有這個簡單的方法:

public int divide(int a, int b) throws ArithmeticException {
        if (b == 0) {
            throw new ArithmeticException("Division by 0");
        } else {
            return a / b;
        }
    }

我想對 JUnit 進行測試。

我做了如下:

@Test(expected = ArithmeticException.class) // Expected this exc
    public void testDivideWhenDivisorIsZero() {
        int result = c.divide(1, 0);
    }

它“返回”一條綠色條線(“測試成功完成”)。

  • 這是 JUnit 測試此方法的正確方法,還是我應該在該測試中放置try-catch子句?

編輯

此 JUnit 測試是否與以下測試等效?

@Test
    public void testDivideWhenDivisorIsZero() {
        try{
            c.divide(1, 0);
            fail("Expected ArithmeticException");
        } catch(ArithmeticException e) {

        }
    }

你的測試看起來是正確的,你不應該在單元測試中使用try..catch塊。 有很多方法,其中一種是你的。 但是對於您的方法,我想使用:

try {
    return a / b;
} catch (ArithmeticException e) {
    throw new ArithmeticException("Division by 0");
}

讓異常被拋出,並捕獲它。 它比在任何操作之前檢查值更干凈(這種情況很少發生)

你這樣做的方式對我來說似乎很好。

在這種情況下,它應該適合您的需要。 盡管如此,我個人更喜歡使用 try-catch-block 來完成。 正如你所提議的,這非常等價。 我認為如果你使用 try-catch-block 會有一些優勢。

首先,您可以斷言,如果拋出的異常的錯誤消息實際上與您已排除的一樣,而且您可以確定該異常實際上是在您的被測方法期間發生的,而不是在您的初始化邏輯期間發生的。 為了更清楚一點:

public int divide(int a, int b) throws ArithmeticException {
        if (b == 0) {
            throw new ArithmeticException("Division by 0");
        } else if(a<b){
            //I know, that this condition is pretty senseless. It's for demonstration only.
            throw new ArithmeticException("a is smaller than b");
        } else{
            return a / b;
        }
    }

然后您可以像這樣測試您的方法,並且可以確定拋出了正確的異常:

@Test
    public void testDivideWhenDivisorIsZero() {
        try{
            c.divide(1, 2);
            fail("Expected ArithmeticException");
        } catch(Exception e) {
            if(e instanceof ArithmeticException){
               Assert.assertTrue(e.getMessage().equals("a is smaller than b"));
            }else{
               fail("The wrong Exception was thrown" + e.toString())
            }
        } 
    }

但正如我所說,您的嘗試完全符合需求。

生產代碼:既不需要捕獲也不需要聲明異常,我建議避免兩者。

public static int divide(int a, int b) {
    return a / b;
}

如果您想與您的 API 用戶溝通可以引發 ArithmeticException,那么您應該在 javadoc 中進行。

測試代碼: JUnit5使斷言異常變得更加容易。

@Test
void divide_whenDenominatorIsZero_shouldThrow() {
    assertThrows(ArithmeticException.class, () -> divide(1, 0));
}

暫無
暫無

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

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