有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JUnit测试divide()方法的java正确方法

我有一个简单的方法:

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

我想测试一下

我做了如下工作:

@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) {

        }
    }

共 (3) 个答案

  1. # 1 楼答案

    生产代码: 捕获或声明异常都不是必需的,我建议避免两者

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

    如果您想与您的API用户通信可以抛出算术异常,那么您应该在javadoc中这样做

    测试代码: JUnit5使asserting exceptions更加容易

    @Test
    void divide_whenDenominatorIsZero_shouldThrow() {
        assertThrows(ArithmeticException.class, () -> divide(1, 0));
    }
    
  2. # 2 楼答案

    您的测试看起来是正确的,您不应该在单元测试中使用try..catch块。有很多方法,其中一种是你的。但对于您的方法,我想使用:

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

    让异常被抛出,并捕获它。它比在任何操作之前检查值更干净(这种情况很少发生)

  3. # 3 楼答案

    我觉得你这样做很好

    在这种情况下,它应该适合你的需要。尽管如此,我个人还是更喜欢用try-catch块。正如你所建议的,这是相当等价的。我认为如果你使用try-catch块,你会有一些优势

    首先,如果抛出异常的errormessage实际上与您所预期的一样,并且您可以确定异常确实发生在您的测试方法期间,而不是在您的初始化逻辑期间,那么您可以断言。 要让这一点更清楚一点:

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

    但正如我所说,你的尝试完全符合需要