java - 读取包含输入值的文件并使用结果生成 .out

标签 java linux unit-testing testing

我有一个 Java 文件,它从用户处接收两个整数并打印出数字的总和,该文件称为 JavaAdd.java 。为了测试这个文件,我需要创建一个包含可能的测试数字的文件,称为 JavaAddTest。当我创建 JavaAddTest 时,第一行如下所示:

2 2

当我运行脚本时:

java JavaAdd < JavaAddTest

我将输出输出到控制台:

Please input 2 ints:
The sum of the 2 values are: 4

这就是我想要的。但我希望能够使用一组数字填充 JavaAddTest,例如:

2 2
0 2
-2 -2
10 10 

并且能够得到如下输出:

Please input 2 ints:
The sum of the 2 values are: 4
Please input 2 ints:
The sum of the 2 values are: 2
Please input 2 ints:
The sum of the 2 values are: -4
Please input 2 ints:
The sum of the 2 values are: 20

我可以在 Linux 环境中执行此操作吗?我必须对 JavaAddTest 做什么才能使其能够读取我的所有输入?

最佳答案

JUnit tutorial link -> see Parameterized test in it for Junit

public class JavaAdd {

public void add(int a, int b) {
    System.out.println("The sum is " + (a + b));
}
}

Junit 类

@RunWith(Parameterized.class)
public class JavaAddTest {

int a, b;

public JavaAddTest(int a, int b) {
    this.a = a;
    this.b = b;
}

@Parameterized.Parameters
public static Collection addNumberInfo() {
 // if you want to read the numbers from file.

 // read here and create array and return it.


    return Arrays
            .asList(new Integer[][] { { 2, 2 }, { 3, 4 }, { 19, 5 }, { 22, 6 }, { 23, 7 } });
}

@Test
public void testAdd() {
    JavaAdd add = new JavaAdd();
    add.add(a, b);
}

}

以下代码的输出

The sum is 4
The sum is 7
The sum is 24
The sum is 28
The sum is 30

希望这就是您正在寻找的内容。

关于java - 读取包含输入值的文件并使用结果生成 .out,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26134765/

相关文章:

linux - 我在哪里可以找到 amazon linux 上的 apxs?

ios - 如何从 OCMock 开始并检查方法是否被调用

java - Jersey,JAXB 并获取一个扩展抽象类的对象作为参数

java.lang.ClassCastException : org. hibernate.internal.QueryImpl 无法转换为 com.models.User

linux - unix - 文件的头部和尾部

linux - 获取linux中每个设备的内存映射

javascript - 在 Angular 单元测试指令中注入(inject)过滤器

c++ - C++中的依赖注入(inject)

java - Handler.postAtTime 与 Handler.postDelayed

java - 在 NetBeans 中,如何将 jMenuBar 添加到 JPanel?