//这是我的主类,当我在这个类中调用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。
答案 0 :(得分:0)
添加一个初始化nodes
的语句可以让你摆脱异常 -
@Before
public void setUp() {
temp = new HNet ();
temp.nodes = new NodeList();
}
另外,建议你尝试改进几点 -
main
方法和CheckNumNodes()
测试方法之间的差异。