如何利用JUnit开展一个简单的单元测试(测试控制台输出是否正确)

待测类(CreateString)如下:

public class CreateString {
    public void createString() {
	//Output the following string "1 2 3"
	System.out.print("1 2 3
");
	
	//Output the following string "1 2 3"
	System.out.print("1 "+"2 "+"3
");
	
	//Output the following string "1 2 3"
	System.out.print(new String("1 2 3
"));
	
	//Output the following string "1 2 3"
	System.out.print(new String("1 2 3
"));		
   }

}


开始编写测试类(CreateStringTest)如下:

  1. 在CreateString.Java 文件上右键(或Ctrl+N),弹出下图:
    如何利用JUnit开展一个简单的单元测试(测试控制台输出是否正确)

  2. 选择 JUnit test case 或者 Test Suite,弹出下图:
    如何利用JUnit开展一个简单的单元测试(测试控制台输出是否正确)

  3. 编写如下测试类代码

    import static org.junit.Assert.*; // Junit 提供断言 assert
    import java.io.ByteArrayOutputStream; // 输出缓冲区
    import java.io.PrintStream; // 打印输出流
    import org.junit.Test; // 提供测试

    public class CreateStringTest {
    // 做三件事情:定义打印输出流(PrintStream console)、输出字节流数组 bytes、新建一个待测对象createString
    PrintStream console = null;
    ByteArrayOutputStream bytes = null;
    CreateString createString;

     @org.junit.Before              // 预处理
     public void setUp() throws Exception {
     
         createString = new CreateString();
     	
         bytes = new ByteArrayOutputStream();
         console = System.out;
    
         System.setOut(new PrintStream(bytes));
    
     }
    
     @org.junit.After              // 后处理
     public void tearDown() throws Exception {
     
        System.setOut(console);
     }
    
     @org.junit.Test               // 测试
     public void testResult() throws Exception {
         createString.createString();        // 调用方法createString() 输出一系列字符串到 (输出字节流数组)bytes
    
         String s = new String("1 2 3
    "+"1 2 3
    "+"1 2 3
    "+"1 2 3
    ");        // 作为 Oracle
         assertEquals(s, bytes.toString());  // 比较 Oracle 和 实际输出的值 bytes, PS 需要将数组对象 bytes 转换为字符串。 
     }
    

    }