本文介绍了Junit使用文件输入参数化测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在我的API单元测试中使用参数化测试的查询。现在,而不是像

I have a query about using parameterized tests for my unit testing of my APIs. Now instead of building an arraylist like

Arrays.asList(new Object[]{
   {1},{2},{3}
});

我想逐个读取文件中的行并将它们填入数组中。
这样一切都会被推广。任何人都可以通过示例向我建议任何这样的方法吗?

I want to read lines in the file one by one split them space and fill them in the array.This way everything would be generalized. Can anyone suggest me any such method with example?

还有一种方法可以在不将各种参数声明为私有成员并在构造函数中初始化它的情况下进行测试测试单位?

Also is there a way that I could be testing without declaring various arguments as the private members and initializing them in the constructor of the test unit?

编辑:Duncan提出的代码

Code as asked by Duncan

@RunWith(Parameterized.class)
public class JunitTest2 {

    SqlSession session;
    Integer num;
    Boolean expectedResult;
    static BufferedInputStream buffer = null;

    public JunitTest2(Integer num, Boolean expected){
        this.num = num;
        this.expectedResult = expected;
    }

    @Before
    public void setup() throws IOException{
        session = SessionUtil.getSqlSessionFactory(0).openSession();
        SessionUtil.setSqlSession(session);
        buffer = new BufferedInputStream(getClass().getResourceAsStream("input.txt"));
        System.out.println("SETUP!");
    }

    @Test
    public void test() {
        assertEquals(expectedResult, num > 0);
        System.out.println("TESTED!");
    }

    @Parameterized.Parameters
    public static Collection getNum() throws IOException{
        //I want my code to read input.txt line by line and feed the input in an arraylist so that it returns an equivalent of the code below

        return Arrays.asList(new Object[][]{
            {2, true},
            {3, true},
            {-1, false}
        });
    }
    @After
    public void tearDown() throws IOException{
        session.close();
        buffer.close();
        System.out.println("TEARDOWN!");
    }
}

另外我的input.txt如下:

Also my input.txt will be as follows:

2 true
3 true
-1 false


推荐答案

@RunWith(JUnitParamsRunner.class)
public class FileParamsTest {

    @Test
    @FileParameters("src/test/resources/test.csv")
    public void loadParamsFromFileWithIdentityMapper(int age, String name) {
        assertTrue(age > 0);
    }

}

支持从CSV文件加载数据。

JUnitParams has support for loading the data from a CSV file.

CSV文件将包含

1,true
2,false

这篇关于Junit使用文件输入参数化测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:46