首页 > 解决方案 > 针对多种情况通过 dataflowinout 流欺骗用户输入

问题描述

在一个作业中,我被要求为我的 MVC 提供一个测试用例,它同时测试控制器和视图类的功能。除了测试用例的视图类之外,我还创建了一个扩展视图类的 testView 类。使用相同的方法和辅助方法,我试图在不同点实现欺骗用户输入。这种欺骗的一个例子可能是它作为打印提示,接受输入,打印打印,接受输入。打印提示和输入都是方法,它们被定义为视图类中与用户的唯一交互,但是在创建测试用例时,我似乎无法注入我想测试我的类功能的自主代码。

public class TestView extends View {
    private Controller newGame;
    private int lineIncrement = 0;

    @Override
    public void sysOutput(String prompt) {
        System.out.println(prompt);
    }

    @Override
    public void showCard(String suit, String value) {
        System.out.println("Card: " + suit + value);
    }

    /**
     *
     * @return sends the input from the user back to the controller for processing
     */
    @Override
    public String sysInput() {
        Scanner myObj = new Scanner(System.in);  // Create a Scanner object
        String input = myObj.nextLine();  // Read user input
        return input;
    }

    //used to get stream of input from the test cases
    public void userInputHelper(String testInput){
        ByteArrayInputStream in = new ByteArrayInputStream(testInput.getBytes());
        System.setIn(in);
        lineIncrement++;
    }

上面是辅助方法和用户输入检索方法,下面是这些方法在测试用例中的用法

    /**
     *  test the ability to interact with the getting the chip amount
     */
    public void testGetChips() {
        String[] actions = {"500", "50"};
        userInputHelper(actions[0]);
        userInputHelper(actions[1]);
        new Controller(this);
        newGame.
        assertEquals("500", newGame.getPlayer().getAllocateBoughtChips());
        lineIncrement = 0;
    }

标签: javatestingjava.util.scanneruser-inputinputstream

解决方案


推荐阅读