Dis*_*ser 1 java junit nullpointerexception
每当我尝试使用JUnit测试我的代码时,我都会收到NullPointerException - 即使我在运行实际程序时没有得到该异常.给我例外的那一行是:
assertEquals(0.0, TweetClassification.tweetType[TweetClassification.SIGNIF_OTHER].likelihoodA);
Run Code Online (Sandbox Code Playgroud)
它正在测试的TweetClassification类的开头如下:
public class TweetClassification
{
// CONSTANTS =============================================
public static final int TCNUMBER = 5; // number of TweetCategories (including the null category)
// using constants to indicate the names of the TweetCategories, so that they could be renumbered
public static final int NULLTWEET = 0;
public static final int SIGNIF_OTHER = 1;
public static final int FRIENDS = 2;
public static final int WORK = 3;
public static final int FOOD = 4;
public static final TweetCategory[] tweetType = new TweetCategory[TCNUMBER];
...
Run Code Online (Sandbox Code Playgroud)
(TweetCategory是另一个在包中单独定义的类.)所以我意识到这个代码初始化了数组而不是它的成员,这可能就是为什么我得到了异常(?)但事实是,我做了初始化TweetClassification的主要方法内的数组成员如下:
for (int i=0; i<TCNUMBER; i++)
{
tweetType[i] = new TweetCategory();
}
Run Code Online (Sandbox Code Playgroud)
但是如果我尝试使用常量在main方法之外移动这个for循环,我会得到一个语法错误 - 我认为你不应该在方法之外使用for循环.所以我不确定如何正确地初始化类以使JUnit工作 - 要么我在main方法之外执行它并得到语法错误,要么我在main方法中执行它并获得NullPointerException.有任何想法吗?
您需要将init代码移动到静态初始化程序块中,如下所示:
public class TweetClassification
{
//...
public static final TweetCategory[] tweetType = new TweetCategory[TCNUMBER];
static
{
for (int i=0; i<TCNUMBER; i++)
{
tweetType[i] = new TweetCategory();
}
}
//...
}
Run Code Online (Sandbox Code Playgroud)
这可以确保在加载类时(即在程序或测试中的任何位置首次使用它之前)正确初始化静态变量.
| 归档时间: |
|
| 查看次数: |
2560 次 |
| 最近记录: |