• 如何利用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),弹出下图:

    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
      "+"1 2 3
      "+"1 2 3
      "+"1 2 3
      ");        // 作为 Oracle
           assertEquals(s, bytes.toString());  // 比较 Oracle 和 实际输出的值 bytes, PS 需要将数组对象 bytes 转换为字符串。 
       }
      

      }


  • 相关阅读:
    18.12.30 【sssx】Trie图
    18.12.30 【sssx】线段树
    18.12.25 POJ 1039 Pipe
    18.12.25 POJ 3525 Most Distant Point from the Sea(半平面+二分)
    18.12.25 POJ 1228 Grandpa's Estate
    18.12.22 luogu P3047 [USACO12FEB]附近的牛Nearby Cows
    18.12.21 DSA 中缀表达式的值
    18.12.21 luogu P3650 [USACO1.3]滑雪课程设计Ski Course Design
    18.12.21 【USACO】Times17
    18.12.20 DSA Full Tank?(DP+BFS)
  • 原文地址:https://www.cnblogs.com/juking/p/5239987.html
Copyright © 2020-2023  润新知