如何利用JUnit開展一個簡單的單元測試(測試控制台輸出是否正確)


待測類(CreateString)如下:

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

}


開始編寫測試類(CreateStringTest)如下:

  1. 在CreateString.Java 文件上右鍵(或Ctrl+N),彈出下圖:

  2. 選擇 JUnit test case 或者 Test Suite,彈出下圖:

  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\n"+"1 2 3\n"+"1 2 3\n"+"1 2 3\n");        // 作為 Oracle
         assertEquals(s, bytes.toString());  // 比較 Oracle 和 實際輸出的值 bytes, PS 需要將數組對象 bytes 轉換為字符串。 
     }
    

    }



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM