我有一个关于在单元测试中使用参数化测试的问题,现在我不想像这样构建一个数组列表:
Arrays.asList(new Object[]{
{1},{2},{3}
});
我希望能够逐行读取文件并将其按空格分割填入数组中。这样一来,所有内容都会被泛化。有人能给我提供一个带有示例的方法吗?
此外,是否有一种方法可以在不将各种参数声明为私有成员并在测试单元的构造函数中初始化它们的情况下进行测试?
编辑:如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将如下所示:
2 true
3 true
-1 false
@Parameter
进行注释(请参见此示例)。 - user180100