关于控制台输入的代码怎么跑单元测试的问题记录

今天写了个控制台输入的代码,准备跑JUnit做单元测试,发现无法正常运行。网上搜了下,发现一个比较好的解决办法:https://stackoverflow.com/questions/1647907/junit-how-to-simulate-system-in-testing

办法是在单元测试里重新分配“标准”输入流,来模拟控制台输入。下面是代码:

        String testOrder = "this is a order!";
        String testOrderResult;

        InputStream si = System.in;
        try{
            //重新分配“标准”输入流
            System.setIn(new ByteArrayInputStream(testOrder.getBytes()));

            Console console = new Console();
            testOrderResult = console.consoleBySystemIn();
        }finally {
            System.setIn(si);
        }

        System.out.println(testOrder);
        assertTrue(testOrder.equals(testOrderResult));

以后写需要控制台输入的单元测试,就可以用上面的方法来测啦~

原文地址:https://www.cnblogs.com/xujanus/p/8427919.html