[英]JUnit Testing: It throws java.lang.NullPointerException when testing a pair of String related setter and getter
here is my class that needed to test: 这是我的课程,需要测试:
public class RankingTableModel {
/**
* filePath stores the path of a csv file.
*/
private String filePath = "";
/**
* table data represents all the data in the table cells.
*/
private Object[][] table_data;
public String getFilePath () {
return filePath;
}
public void setFilePath (String filePath) {
this.filePath = filePath;
}
here is my JUnit test class (for @Before, @After, .etc, I didn't do any thing special, just print some messages): 这是我的JUnit测试类(对于@ Before,@ After,.etc,我没有做任何特别的事情,只打印了一些消息):
public class RankingTableModelTest {
private static final Object[][] data = {
{"US", new Integer(1), new Integer(2), new Integer(2),
new Integer(3)},
{"UK", new Integer(2), new Integer(2), new Integer(1),
new Integer(2)},
{"CHN", new Integer(3), new Integer(1), new Integer(3),
new Integer(1)},
};
private static final String file_path = "test";
private RankingTableModel test_model;
@Test
public void setFilePathAndGetFilePath() {
System.out.println("Testing setFilePath and getFilePath.");
test_model.setFilePath(file_path);
assertEquals(test_model.getFilePath(),"test");
}
} }
When I run the test, it throws an exception: java.lang.NullPointerException at * .RankingTableModelTest.setFilePathAndGetFilePath(RankingTableModelTest.java:51) 51 is the number of line : test_model.setFilePath(file_path); 运行测试时,它将引发异常: * .RankingTableModelTest.setFilePathAndGetFilePath(RankingTableModelTest.java:51)处的java.lang.NullPointerException 51是行号:test_model.setFilePath(file_path);
What is the problem with my code? 我的代码有什么问题? Thx :)
谢谢 :)
You never instantiated test_model
. 您从未实例化
test_model
。
Somewhere, you'll need test_model = new RankingTableModel();
在某个地方,您将需要
test_model = new RankingTableModel();
or something similar. 或类似的东西。
You have just declared test_model: 您刚刚声明了test_model:
private RankingTableModel test_model;
Not, initialized it. 不,初始化它。
private RankingTableModel test_model = new RankingTableModel();
Above line will fix your problem. 以上行将解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.