[英]Junit test of method with Scanner and System.in (Java)
I'm new to programmming and I have this simple method: 我是编程的新手,我有一个简单的方法:
public double input() {
double result = 0;
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextDouble()) {
result = scanner.nextDouble();
} else {
System.out.print("Please, type numbers!\n");
}
return result;
}
The question is how to simulate (emulate) user's input from the keyboard in junit test. 问题是在junit测试中如何从键盘模拟(模拟)用户输入。
Pass a Scanner
as input parameter to the method you want to test. 将
Scanner
作为输入参数传递到要测试的方法。 In your test code, you can create a Scanner
instance from a string: 在测试代码中,您可以从字符串创建
Scanner
实例:
Scanner scanner = new Scanner("the sample user input");
And then in the production code, you can pass new Scanner(System.in)
to the method. 然后在生产代码中,可以将
new Scanner(System.in)
传递给该方法。
You should read more about dependency injection . 您应该阅读有关依赖注入的更多信息。
Your Class shouldn't be tightly coupled with other classes.
您的班级不应与其他班级紧密结合。 Dependencies can be provided to objects at multiple levels according to the need.
可以根据需要向多个级别的对象提供依赖项。
- Using constructor/setter if it is a field.
如果是字段,则使用构造函数/设置器。
- Using method parameters if the scope is just in a method.
如果范围仅在方法中,则使用方法参数。
In your case as soon as you say:- 就您而言,只要您说:-
Scanner scanner = new Scanner(System.in);
Now your code is fully coupled with System.in
stream. 现在,您的代码已与
System.in
流完全耦合。 Instead you should inject this as a parameter to your method in below format. 相反,您应该以以下格式将其作为方法的参数注入。
public double input(InputStream inputStream) {
double result = 0;
Scanner scanner = new Scanner(inputStream);
if (scanner.hasNextDouble()) {
result = scanner.nextDouble();
} else {
System.out.print("Please, type numbers!\n");
}
return result;
}
Now from your main code you can call it with System.in
. 现在,可以从您的主要代码中使用
System.in
进行调用。 From your test class you call it with any InputStream. 在测试类中,可以使用任何InputStream调用它。 Mostly we use a
mock/stub
for it. 通常,我们为此使用
mock/stub
。
Note:- Above it just an example, and can be change according to need. 注意:-上面只是一个示例,可以根据需要进行更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.