使用 Scanner 对用户输入进行 junit 测试 [英] junit testing for user input using Scanner

查看:19
本文介绍了使用 Scanner 对用户输入进行 junit 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在一个使用 Scanner 类接受输入的类中测试一个方法.

I have to test a method in a class which takes an input using Scanner class.

package com.math.calculator;

import java.util.Scanner;

public class InputOutput {

    public String getInput() {
        Scanner sc = new Scanner(System.in);
        return sc.nextLine();
    }
}

我想使用 JUnit 测试它,但不知道如何去做.

I want to test it using JUnit but not sure how to do it.

我尝试使用以下代码,但不起作用.

I tried using the following code but it wont work.

package com.math.calculator;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class InputOutputTest {

    @Test
    public void shouldTakeUserInput() {
        InputOutput inputOutput= new InputOutput();

        assertEquals("add 5", inputOutput.getInput());
    }
}

我也想用 Mockito 尝试一下(使用 mock... when ... thenReturn)但不知道如何去做.

I want to also try it with Mockito (using mock... when ... thenReturn) but not sure how to do it.

推荐答案

您可以使用 System.setIn() 方法更改 System.in 流.

You can change the System.in stream using System.setIn() method.

试试这个,

@Test
public void shouldTakeUserInput() {
    InputOutput inputOutput= new InputOutput();

    String input = "add 5";
    InputStream in = new ByteArrayInputStream(input.getBytes());
    System.setIn(in);

    assertEquals("add 5", inputOutput.getInput());
}

您刚刚修改了 System.in 字段.System.in 基本上是一个从 console 读取的 InputStream (因此您在控制台中输入).但是你只是修改了它,让系统从提供的 inputstream 中读取.所以它不会再从控制台读取,而是从提供的输入流读取.

You have just modified the System.in field. System.in is basically an InputStream which reads from the console (hence your input in the console). But you just modified it and let the system to read from the provided inputstream instead. So it wont read from console anymore but from the inputstream provided.

这篇关于使用 Scanner 对用户输入进行 junit 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆