JUnit 测试:在测试一对 String 相关的 setter 和 getter 时抛出 java.lang.NullPointerException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19694096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JUnit Testing: It throws java.lang.NullPointerException when testing a pair of String related setter and getter
提问by chygo
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);
当我运行测试时,它抛出一个异常: java.lang.NullPointerException at *.RankingTableModelTest.setFilePathAndGetFilePath(RankingTableModelTest.java:51) 51 是行数: test_model.setFilePath(file_path);
What is the problem with my code? Thx :)
我的代码有什么问题?谢谢 :)
采纳答案by Dawood ibn Kareem
You never instantiated test_model
.
您从未实例化test_model
.
Somewhere, you'll need test_model = new RankingTableModel();
or something similar.
在某个地方,您将需要test_model = new RankingTableModel();
或类似的东西。
回答by Akshay
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.
以上行将解决您的问题。