gpt4 book ai didi

java - 单元测试一个整体的主要方法

转载 作者:行者123 更新时间:2023-11-30 10:58:57 25 4
gpt4 key购买 nike

有一个main 方法和其中的所有逻辑。如何在 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();
}
}

最佳答案

整个逻辑都在你的 main 中,所以测试它更像是系统测试(集成测试),最好的方法是为每个方法编写单元测试,最后你可以测试 main 以确保你的所有方法都正常工作在一起很好。

来自 Stanford University Lecture Notes :

"Unit tests: Focused, low-level; test individual methods or pieces of methods. Easier to ensure that each piece of code is tested Easier to write and run May not catch problems coming from interactions between different pieces of code System tests (or integration tests): test the entire system working together. Good for making sure that all of the pieces work together Can generate more complex interactions between pieces Harder to write and run."

关于java - 单元测试一个整体的主要方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32074388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com