在用Junit编写测试文件的时候经常会碰到一些方法,他们会在控制台产生一些输出,应该怎么判断方法的输出确实是我们预期的那样的呢?
下面提供一个简单的判断方法:(其他方法感觉好复杂OTL)
public class helloWorld {
public void printHelloWorld() {
System.out.println("HelloWorld");
}
}
helloWorld类包含一个打印方法,接下类编写测试检测他的输出是否为”HelloWorld“。
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.*;
public class helloWorldTest {
helloWorld helloWorld = new helloWorld();
private PrintStream console = null;
private ByteArrayOutputStream bytes = null;
@Before
public void init() {
bytes = new ByteArrayOutputStream();
console = System.out;
System.setOut(new PrintStream(bytes));
}
@After
public void tearDown() {
System.setOut(console);
}
@Test
public void printHelloWorld() {
helloWorld.printHelloWorld();
assertEquals("HelloWorld", bytes.toString().trim());
}
测试通过!
原文:https://www.cnblogs.com/owczhlol/p/12655046.html