这是我的TestClass。我尝试解析CSV文件并创建一个Object [] [](调用data
)。当我尝试像参数一样给data
时,它会调用nullpointer。我不知道为什么会失败。当我提供像硬核代码这样的数据时,它确实有效。请解释一下,我不明白
@RunWith(Parameterized.class)
public class TestJUnit {
public int firstParameter;
public int secondParameter;
public String operation;
public int expectedResult;
public static Object[][] data;
public TestJUnit(int firstParameter, int secondParameter, String operation, int expectedResult) {
this.firstParameter = firstParameter;
this.secondParameter = secondParameter;
this.expectedResult = expectedResult;
this.operation = operation;
}
@BeforeClass
public void makeData() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\third\\IdeaProjects\\MyJunit\\src\\test\\java\\com\\myLogicTest\\datafile.csv"));
ArrayList<Object[]> tempArray = new ArrayList<Object[]>();
String newLine;
Object[] oneString;
while ((newLine = reader.readLine()) != null) {
oneString = newLine.split(";");
tempArray.add(oneString);
}
data = new Object[tempArray.size()][];
for (int i = 0; i < data.length; i++) {
Object[] row = tempArray.get(i); data[i] = row; }
}
@Test
public void checkCalculator() {
final Calculator calculator = new Calculator(firstParameter, secondParameter, operation);
int result;
if (operation.equals("*")) {
result = calculator.multi();
Assert.assertTrue("Результат (" + result + ") не равен" + expectedResult, result == expectedResult);
}
else if (operation.equals("+")) {
result = calculator.plus();
Assert.assertTrue("Результат (" + result + ") не равен" + expectedResult, result == expectedResult);
}
else if (operation.equals("-")) {
result = calculator.minus();
Assert.assertTrue("Результат (" + result + ") не равен" + expectedResult, result == expectedResult);
}
else if (operation.equals("/")) {
result = calculator.del();
Assert.assertTrue("Результат (" + result + ") не равен" + expectedResult, result == expectedResult);
}
}
@Parameterized.Parameters(name = "{index}: Действие {0} {2} {1} = {3}")
public static Collection<Object[]> getTestData() {
return Arrays.asList(data
/* new Object[][]{ //<<<NULLPOINTER HERE
{2, 2, "*", 4},
{2, 0, "+" , 2},
{2, 2,"/", 1},
{0, 2,"-",-2}
}*/);
}
}
答案 0 :(得分:0)
问题出现在注释@BeforeClass中,当我们使用参数化测试时,@ Before和@BeforeClass运行不是第一个!在我的情况下,我需要在方法getTestData()中调用方法makeData(),如下所示:
@Parameterized.Parameters(name = "{index}: Действие {0} {2} {1} = {3}")
public static Collection<Object[]> getTestData() {
makedata(); // <<<<<I NEED USE IT HERE!
return Arrays.asList(data
/* new Object[][]{ //<<<NULLPOINTER HERE
{2, 2, "*", 4},
{2, 0, "+" , 2},
{2, 2,"/", 1},
{0, 2,"-",-2}
}*/);