我刚完成家庭作业,并在大学通过了自动评估。我想使用JUnit
进行单元测试,现在我知道这是正确的。
我学会了如何override and read standard output和simulate 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
失败的字符串的完整差异吗?
答案 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)
注意日志中的一些细节 -
为了确保一致性,我使用了Apache Maven 3.3.9
和maven-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>