IntelliJ IDEA控制台junit不能用Scanner输入
PS:IDE版本IntelliJ IDEA 2019.3.3 x64
测试代码:
import org.junit.Test;
import java.util.Scanner;
public class TestScan {
@Test
public void testScan() {
Scanner scan = new Scanner(System.in);
System.out.print("用户名:");
String userName = scan.nextLine();
System.out.print("密 码:");
String password = scan.nextLine();
System.out.println("用户名:" + userName);
System.out.println("密 码:" + password);
}
}
错误运行:
说明:
- 这段代码在eclipse是可以运行的,在eclipse的Junit单元测试中是可以输入内容的
- 使用Junit运行单元测试时,为什么不能从控制台输入任何内容?由于Junit是自动测试单元,不支持手动输入!
- https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000556544-Why-can-t-I-input-anything-from-console-when-i-run-unit-test-with-JUNIT
解决方法:
方法一:使用main方法
测试代码:
import java.util.Scanner;
public class TestScan {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("用户名:");
String userName = scan.nextLine();
System.out.print("密 码:");
String password = scan.nextLine();
System.out.println("用户名:" + userName);
System.out.println("密 码:" + password);
}
}
运行结果:
方法二:更改vmoptions配置文件
步骤:
- 找到IntelliJ IDEA安装目录
- 进入bin文件夹
- 如果你的系统是32位的,找到【idea.exe.vmoptions】,使用记事本打开;如果你的系统是64位的,找到【idea64.exe.vmoptions】,使用记事本打开
- 在文本最后添加 -Deditable.java.test.console=true 然后保存
- 重启IntelliJ IDEA
测试代码:
import org.junit.Test;
import java.util.Scanner;
public class TestScan {
@Test
public void testScan() {
Scanner scan = new Scanner(System.in);
System.out.print("用户名:");
String userName = scan.nextLine();
System.out.print("密 码:");
String password = scan.nextLine();
System.out.println("用户名:" + userName);
System.out.println("密 码:" + password);
}
}
运行结果:
方法三:更改Edit Custom VM Options
说明:
此方法和方法二类似,但是此方法修改的是IDEA加载时的vmoptions配置文件(【C:\Users\XiaoGangpao\.IntelliJIdea2019.3\config】),而我安装的目录是(【D:\IntelliJ IDEA 2019.3.3\bin】)
IDEA加载时的vmoptions配置文件和安装目录bin中的vmoptions配置文件可能不一样
C:\Users\XiaoGangpao\.IntelliJIdea2019.3\config
C: | C盘 |
\Users | User目录 |
\XiaoGangpao | 自己的用户目录 |
\.IntelliJIdea2019.3 | IDEA目录(不是安装目录) |
\config | config目录 |
步骤:
- 在导航找到help ->Edit Custom VM Options
- 弹出的对话框文件中追加 -Deditable.java.test.console=true
测试代码:
import org.junit.Test;
import java.util.Scanner;
public class TestScan {
@Test
public void testScan() {
Scanner scan = new Scanner(System.in);
System.out.print("用户名:");
String userName = scan.nextLine();
System.out.print("密 码:");
String password = scan.nextLine();
System.out.println("用户名:" + userName);
System.out.println("密 码:" + password);
}
}
运行结果: