问题1:我有一个提示输入的程序,其中一个选项是选择选项"t",意思是从文本文件中获取信息。然后提示用户输入文本文件的名称。
问题2:testE()testF()
都意味着无法显示验证输入。我如何显示它们已通过?
到目前为止,我的测试是这样的,大多数都是单输入
import java.io.ByteArrayInputStream;
import package.App;
import org.junit.Test;
public class AppTest {
@Test
public void testA(){
testApp("1");
}
@Test
public void testB(){
testApp("2");
}
@Test
public void testC(){
testApp("3");
}
@Test
public void testD(){
testApp("a");
}
@Test
public void testE(){
testApp("hello");
}
@Test
public void testF(){
testApp("");
}
@Test
public void testG(){
testApp("t");
}
public void testApp(String a){
System.out.println();
ByteArrayInputStream in = new ByteArrayInputStream(a.getBytes());
System.setIn(in);
App.main(null);
System.out.println();
}
}
这是主要类别:
import java.util.Scanner;
public class App {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter '1' , '2' or '3' for individual calulations based on formatted input from the given problem" + "n" +
"Enter 't' for input from a text file");
System.out.print("Please select the mode from which to run:");
String input = "";
input = scan.nextLine();
while(input.length()!= 1){
System.out.println();
System.out.println("Invalid input, valid entries. Please try again.");
System.out.println("Enter '1' , '2' or '3' for individual calulations based on formatted input from the given problem" + "n" +
"Enter 't' for input from a text file");
System.out.print("Please select the mode from which to run:");
input = scan.nextLine();
}
System.out.println();
char c = input.charAt(0);
new ProductList(c);
scan.close();
}
}
不能那样做。
停下来,思考您要测试的内容。当然不是Java控制台输入的功能,而是您计算的结果,对吗?
重构代码以将数据输入与计算分离。去掉静态方法中的逻辑,尤其是主方法。使用对象定向创建适当的组件,可能是Calculator
和DataProvider
静态main只会把东西连接在一起,没有其他逻辑。
根据Calculator编写测试,但这一次将它从测试内部连接在一起,以及可以为测试提供测试值的不同DataProvider(但这与cosole无关)。
现在写很多很酷的单元测试:)