简体   繁体   English

如何在 JUnit 中测试错误路径和极端情况?

[英]How to test for error paths and corner cases in JUnit?

I have code and I have to write JUnit tests for it.我有代码,我必须为它编写 JUnit 测试。 I already wrote test for happy path, but I have to write tests for corner cases and error paths.我已经为快乐路径编写了测试,但我必须为极端情况和错误路径编写测试。 Can you help me with finding solution pls.你能帮我找到解决方案吗?

public String reverseWords(String input) {
    String oneOrMoreSpaces = "\\s+";
    String[] words = input.split(oneOrMoreSpaces);
    String completeAnagram = "";

    for (int i = 0; i < words.length; i++) {
        char[] symbol = words[i].toCharArray();
        char newSymbolSequence;
        int j = symbol.length - 1, k = 0;

        while (k < j) {
            if (!Character.isAlphabetic(symbol[k]))
                k++;
            else if (!Character.isAlphabetic(symbol[j]))
                j--;
            else {
                newSymbolSequence = symbol[k];
                symbol[k] = symbol[j];
                symbol[j] = newSymbolSequence;
                k++;
                j--;
            }
        }
        completeAnagram = new String(symbol);
    }
    return completeAnagram;
}

This feels like a homework question .这感觉就像一个家庭作业问题 The exercise is nice enough, though!不过,这项运动已经足够好了! The code seems to contain (at leats) one fault, making it interesting to see at which step you can discover this.该代码似乎包含(至少)一个错误,这使得查看您可以在哪一步发现这一点很有趣。

Some guidelines for addressing this type of problem:解决此类问题的一些指南:

  1. You can only think about testing a method if you know what the functionality is supposed to be.如果您知道功能应该是什么,您只能考虑测试方法。 The short answer here seems to be given a sentence, produce the sentence with each word reversed , but this could use some improvement.这里的简短答案似乎是给了一个句子,生成每个单词颠倒的句子,但这可以使用一些改进。

  2. Once you think you know what the method should do, you can come up with a series of example inputs and outputs.一旦您认为您知道该方法应该做什么,您就可以想出一系列示例输入和输出。 These will eventually be your test cases.这些最终将成为您的测试用例。

  3. By producing examples, you can critically look for complicated ("corner"?) cases.通过生成示例,您可以批判性地寻找复杂的(“角落”?)案例。 What happens if there are no words?如果没有词会发生什么? Should letters be treated the same as punctuation?字母应该和标点符号一样对待吗? What is the effect of reversing a one-letter word?反转一个字母的单词有什么作用? You don't need any code for this, just an understanding of the application domain.您不需要任何代码,只需要了解应用程序域。 Each of these questions may give rise to more examples.这些问题中的每一个都可能产生更多的例子。

  4. Once you have enough examples, you can create test cases for them.一旦你有足够的例子,你就可以为它们创建测试用例。 Parameterized tests seem a natural fit. 参数化测试似乎很自然。

  5. With your requirements-driven test cases up and running, you can then analyze the implementation.随着您的需求驱动的测试用例启动并运行,您可以分析实现。 Is every line / branch covered?是否覆盖了每一行/分支? Is there indeed a test case that exercises the else if branch in the middle of the code?是否确实有一个测试用例在代码中间执行else if分支? If there is code that is not executed, go back to the requirements, and think which example would require this branch.如果有没有执行的代码,回到需求,想想哪个例子会需要这个分支。 Then add that example, until you have full coverage.然后添加该示例,直到您完全覆盖。

  6. Once you have full branch coverage, you may try and deliberately introduce small mistakes in the code.一旦你有完整的分支覆盖,你可以尝试故意在代码中引入小错误。 If you replace a < by a <= , will one of your examples reveal this as a bug?如果您将<替换为< <= ,您的一个示例是否会将其显示为错误? If not, add such an example!如果没有,请添加这样的示例!

If you want to learn more, look for category-partition (step 3), branch coverage (step 5), and mutation coverage (step 6).如果您想了解更多信息,请查找类别分区(第 3 步)、分支覆盖(第 5 步)和变异覆盖(第 6 步)。 For this, you can check out our open access online book Software Testing: From Theory to Practice , which includes videos, slides, and exercises.为此,您可以查看我们的开放获取在线书籍软件测试:从理论到实践,其中包括视频、幻灯片和练习。 Enjoy!享受!

If you need to verify on exceptions you can use Junit @test(expected=Yor exception)如果您需要验证异常,您可以使用 Junit @test(expected=Yor exception)

ex : obj need to be initialized in the class. ex : obj 需要在类中初始化。

@Test(expected=NullPointerException.class)
public void testNullPonterException(){

String val = obj.reverseWords(null);

}

Otherwise you When you need to verify some other properties of the exception, we can use the ExpectedException rule.否则当您需要验证异常的其他一些属性时,我们可以使用 ExpectedException 规则。

@Rule
public ExpectedException exceptionRule = ExpectedException.none();
 
@Test
public void whentestNullPonterExceptionThrown_thenRuleIsApplied() {
    exceptionRule.expect(NullPointerException.class);
    exceptionRule.expectMessage("Invalid Input");
    String val = obj.reverseWords(null);
}

常见的错误和边缘情况是输入为null或空字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM