我试图在JUnit中进行测试,在这里我想测试控制台是否打印出我希望它打印的消息。代码如下所示:
public class MainTestingClass extends TestCase {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@After
public void cleanUpStreams() {
System.setOut(null);
}
@Test
public void testPracticalViewConsole() {
PracticalView view = new PracticalView();
view.PrintResults();
assertEquals("welcome to the macro counting app", outContent.toString());
}
}但出于某种原因,system.out仍然打印到控制台,在测试中我得到:
junit.framework.ComparisonFailure: Expected :欢迎访问宏计数应用程序Actual:
我不知道问题出在哪里。
发布于 2015-11-17 14:43:43
我复制了您的实验,并根据经验发现,这种奇怪行为的原因是超类TestCase (这甚至不是必要的,因为您使用的是JUNIT 4注释)。把它放下,看看它是如何工作的。
而且,虽然严格来说并不是必要的,但是如果您使用PrintStream实例化autoFlush=true,则会更安全:
System.setOut(new PrintStream(outContent, true));发布于 2015-11-17 13:46:33
与System类交互是非常糟糕的解决方案,更不用说System.setOut(null)可能会产生副作用(例如,您将无法在这个JVM的控制台中看到更多的东西)。我不确定它究竟是如何工作的,因为方法是原生的,而javadoc则是模糊的。
测试中的一个良好实践是将代码与不受控制的代码隔离开来(此处为System类)。您应该将System.out.println包装到您自己的类中:
public class Printer {
public void println(Object object) {
System.out.println(object);
}
}然后,您可以使用一个模拟框架(这里是:莫基托)来模拟Printer,执行依赖注入和断言交互:
@Test
public void testPracticalViewConsole(){
Printer printer = mock(Printer.class);
PracticalView view = new PracticalView(printer);
view.PrintResults();
verify(printer, times(1)).println("welcome to the macro counting app");
}编辑:
为了帮助您开始使用mockito,这里有一个您需要的maven依赖项:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
</dependency>这些是用于上述试验的进口品:
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;https://stackoverflow.com/questions/33758387
复制相似问题