拥有主方法及其中的所有逻辑。如何在JUnit中测试(模拟)input.txt?我应该将代码分成较小的部分,以便我可以通过方法调用它吗?文件输入应如下所示
/*
input.txt
add 2
add 2
apply 3
correct result 3 + 2 + 2 = 7
*/
public class Main {
public static void main(String[] args) {
List<Operation> listOperations = new ArrayList<Operation>();
int size = listOperations.size() - 1;
int keepingCount = 0;
try {
File file = new File("input.txt");
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
String[] parts = line.split(" ");
String operationSign = parts[0];
int numberFromLine = Integer.parseInt(parts[1]);
Operation operation = new Operation();
operation.setCalculation(operationSign);
operation.setNumber(numberFromLine);
if (!operation.getCalculation().equals("apply")) {
listOperations.add(operation);
} else {
listOperations.add(operation);
break;
}
}
input.close();
for (int x = 0; x < size; x++) {
if (listOperations.get(x).calculation.equals("add")) {
if (keepingCount == 0) {
keepingCount = listOperations.get(x).number + listOperations.get(size).number;
} else {
keepingCount = listOperations.get(x).number + keepingCount;
}
}
if (listOperations.get(x).calculation.equals("multiply")) {
if (keepingCount == 0) {
keepingCount = listOperations.get(x).number * listOperations.get(size).number;
} else {
keepingCount = listOperations.get(x).number * keepingCount;
}
}
if (listOperations.get(x).calculation.equals("substract")) {
if (keepingCount == 0) {
keepingCount = listOperations.get(x).number - listOperations.get(size).number;
} else {
keepingCount = keepingCount - listOperations.get(x).number;
}
}
if (listOperations.get(x).calculation.equals("divide")) {
if (keepingCount == 0) {
keepingCount = listOperations.get(size).number / listOperations.get(x).number;
} else {
keepingCount = keepingCount / listOperations.get(x).number;
}
}
}
System.out.println(keepingCount);
} catch (Exception ex) {
ex.printStackTrace();
}
}
答案 0 :(得分:1)
整个逻辑在您的主要测试中,这更像是系统测试(集成测试),最好的方法是为每个方法编写单元测试,最后您可以测试main以确保所有方法都正常工作很好。
来自Stanford University Lecture Notes:
“单元测试: 专注,低级; 测试个别方法或方法。 更容易确保每段代码都经过测试 更容易编写和运行 可能无法捕获来自不同代码段之间的交互的问题 系统测试(或集成测试): 测试整个系统一起工作。 有利于确保所有部分协同工作 可以在片段之间产生更复杂的交互 写作和运行更难。“