java test 經驗之談

/**
     * 日誌間諜類
     */
public static class Logget {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();//緩衝
        PrintStream console;
        public List<String> loglist = new ArrayList<>();

        public void listenSTD() {
            console = System.out;//獲取System.out 輸出流的句柄
            System.setOut(new PrintStream(bytes));
        }

        public void listenSTDAndClear() {
            listenSTD();
            loglist.clear();
            bytes.reset();
        }

        public List<String> close() {
            resetSTD();
            for (String s : bytes.toString().split("\r\n")
            ) {
                loglist.add(s);
            }
            return this.loglist;
        }

        private void resetSTD() {
            System.setOut(console);//復位
        }

        public List<String> closeandprintSTD() {
            resetSTD();
            System.out.print(bytes);
            return close();
        }
    }

//使用
logget=new Logget();
logger.listenSTDAndClear();//監聽日誌
日誌打印
日誌打印1
logtext = logget.closeandprintSTD();//釋放監聽,並獲取截留,控制檯輸出原本截留的日誌,logtext是用於校驗的list
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章