简体   繁体   English

JUnit 测试除法()方法的正确方法

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

I've got this simple method:我有这个简单的方法:

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

and I'd like to JUnit test it.我想对 JUnit 进行测试。

I've done as follows:我做了如下:

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

which "returns" a green bar line ("tests finished successfully").它“返回”一条绿色条线(“测试成功完成”)。

  • Is this a correct way to JUnit test this method or should I have put a try-catch clause in that test?这是 JUnit 测试此方法的正确方法,还是我应该在该测试中放置try-catch子句?

EDIT编辑

Would this JUnit test be equivalent with the following?此 JUnit 测试是否与以下测试等效?

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

        }
    }

Your test looks correct, and you should not use try..catch block in unit test.你的测试看起来是正确的,你不应该在单元测试中使用try..catch块。 there are many ways, one of them is yours.有很多方法,其中一种是你的。 But for your method I would like to use:但是对于您的方法,我想使用:

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

Let the exception be thrown, and catch it.让异常被抛出,并捕获它。 it is more clean than checking the value before any action(which that case can be rare to happen)它比在任何操作之前检查值更干净(这种情况很少发生)

The way you did this seems fine to me.你这样做的方式对我来说似乎很好。

It should fit your need in this case.在这种情况下,它应该适合您的需要。 Nonetheless I personally prefering to do it with a try-catch-block.尽管如此,我个人更喜欢使用 try-catch-block 来完成。 Which as you proposed are pretty equivalent.正如你所提议的,这非常等价。 I think you've a few advantages if you do with the try-catch-block.我认为如果你使用 try-catch-block 会有一些优势。

First of all, you can assert, if the errormessage of the thrown exception is actually as you've excepted and in addition you can be sure, that the exception actually happened during your method-under-test and not during your init-logic.首先,您可以断言,如果抛出的异常的错误消息实际上与您已排除的一样,而且您可以确定该异常实际上是在您的被测方法期间发生的,而不是在您的初始化逻辑期间发生的。 To get this a little bit clearer:为了更清楚一点:

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

Then you can test your method like this and you can be sure, that the correct Exception was thrown:然后您可以像这样测试您的方法,并且可以确定抛出了正确的异常:

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

But as I said your attempt fits absolutely the needs.但正如我所说,您的尝试完全符合需求。

Production code: Neither catching nor declaring the exception is necessary, and I recommend avoiding both.生产代码:既不需要捕获也不需要声明异常,我建议避免两者。

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

If you want to communicate to your API user that an ArithmeticException can be thrown, then you should do it in the javadoc.如果您想与您的 API 用户沟通可以引发 ArithmeticException,那么您应该在 javadoc 中进行。

Testcode: JUnit5 made asserting exceptions much more easy.测试代码: 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