gpt4 book ai didi

java - 如何解决NeticaJ Junit中的NullPointerException?

转载 作者:太空宇宙 更新时间:2023-11-04 11:45:03 25 4
gpt4 key购买 nike

//这是我的主类,当我在这个类中调用methodTwo时,我得到numnodes=4,但是当我尝试访问testclass中的methodTwo时,我得到了NullPointerException。

package Netica;

import norsys.netica.Environ;
import norsys.netica.Net;
import norsys.netica.NodeList;
import norsys.netica.Streamer;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

import NeticaTestCases.HNetTest;

public class HNet {
private static long startTime = System.currentTimeMillis();
private static Net net;
private static NodeList nodes;
int numNodes;

public int methodOne() {
System.out.println("we are in first methodOne");
return 1;
}

public int methodTwo() {
numNodes = nodes.size();
System.out.println("we are in 2nd methodTwo");
return numNodes;
}

public static void main(String[] args) {
try {


// Read in the net file and get list of all nodes and also Total
// number of nodes:
net = new Net(neStreamer("DataFiles/KSA_4_Nodes_noisySum.dne"));
nodes = net.getNodes();

HNet temp = new HNet();
temp.methodOne();
System.out.println("numNodes========>"+temp.methodTwo());//get 4

} catch (Exception e) {
}

}
}

//this is my testclass

package NeticaTestCases;

import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.fail;

import Netica.HNet;

public class HNetTest {
HNet temp;

@Before
public void setUp() {
temp = new HNet ();
}

@Test
public void CheckNumNodes() {
temp.methodOne();
System.out.println("numNodes========>"+temp.methodTwo());
}

}

请帮助我解决 junit 测试用例中的 NullPointerException。

最佳答案

添加一条初始化节点的语句应该可以消除异常 -

@Before
public void setUp() {
temp = new HNet ();
temp.nodes = new NodeList();
}

此外,建议您尝试改进一些点 -

  1. 调试 main 方法和 CheckNumNodes() 测试方法之间的差异。
  2. 使用getters and setters

关于java - 如何解决NeticaJ Junit中的NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42434949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com