比较大字符串时,JUnit assertEquals的详细输出更详细

时间:2017-03-08 16:11:31

标签: java maven netbeans junit

我刚完成家庭作业,并在大学通过了自动评估。我想使用JUnit进行单元测试,现在我知道这是正确的。

我学会了如何override and read standard outputsimulate standard input。我给自己写了一个方法:

public static void simulateIn(final String str) {
    // Simulated STDIN
    final ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes());
    System.setIn(in);
}

我按如下方式使用它:

@Test
public void TestOnePlusOne() throws Exception {
    simulateIn("1 1 1 1");
    // Homework assignment executes here
    new Lab01().homework();
    // Expected input. I didn't translate it, but it's just a simple calculator
    assertEquals("Vyber operaci (1-soucet, 2-rozdil, 3-soucin, 4-podil):\n" +
                "Zadej scitanec: \n" +
                "Zadej scitanec: \n" +
                "Zadej pocet desetinnych mist: \n" +
                "1.0 + 1.0 = 2.0\n", outContent.toString());
}

我没有翻译预期的输出,它现在说的无关紧要。重要的是测试失败了,我得到的就是:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running test.TestCalculator
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.097 sec <<< FAILURE!

Results :

Failed tests:   TestOnePlusOne(test.TestCalculator): expected:<...desetinnych mist: 

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0

那是非常无益的。因为我知道赋值是正确的,所以单元测试有问题。我可以获得assertEquals失败的字符串的完整差异吗?

1 个答案:

答案 0 :(得分:0)

尝试重现同样的失败,我尝试了 -

@Test
public void log() {
    Assert.assertEquals("Vyber operaci (1-soucet, 2-rozdil, 3-soucin, 4-podil):\n" +
            "Zadej scitanec: \n" +
            "Zadej scitanec: \n" +
            "Zadej pocet desetinnych mist: \n" +
            "1.0 + 1.0 = 2.0\n", ""); // empty string to make sure this fails
}

从包含上述测试类的模块的根目录的命令行执行命令mvn clean install。它产生了以下日志 -

Running TestOne
true
Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.356 sec <<< FAILURE! - in TestOne
log on log(TestOne)(TestOne)  Time elapsed: 0.007 sec  <<< FAILURE!
org.junit.ComparisonFailure: 
expected:<[Vyber operaci (1-soucet, 2-rozdil, 3-soucin, 4-podil):
Zadej scitanec: 
Zadej scitanec: 
Zadej pocet desetinnych mist: 
1.0 + 1.0 = 2.0
]> but was:<[]>
        at TestOne.log(TestOne.java:17)

注意日志中的一些细节 -

  1. 运行 TestOne - 测试类名称
  2. log(TestOne) - 方法名称
  3. org.junit.ComparisonFailure 失败类型
  4. 预期和实际.. 但是
  5. 为了确保一致性,我使用了Apache Maven 3.3.9maven-surefire-plugin:2.19.1

    <dependencies>
      ...
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
            </plugin>
        </plugins>
    </build>