1
//這是我的主類,當我在這個類中調用methodTwo時,我得到了numnodes = 4,但是當我試圖訪問testTwo時,我得到了NullPointerException。如何解決Junit for NeticaJ中的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異常。
歡迎來到SO。你有沒有試過調試它? –
'nodes'變量未被初始化。你在'main'方法中賦予它一個值,這在你的測試中顯然沒有被調用。這可能會導致NullPointerException。爲了確保它是這樣,你應該調查你的堆棧跟蹤。如果有任何不清楚的地方,請在此粘貼堆棧跟蹤。 –
可能的重複[什麼是NullPointerException,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it ) –