1

//This is my Main Class here when i call methodTwo in this class i got numnodes=4 but when i tried to access methodTwo in testclass i got 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());       
        }   

}

please help me out how to resolve NullPointerException in junit testcases.

Raj
  • 1
  • 1
  • 6
  • Welcome to SO. Have you tried to debug it? – Uwe Allner Feb 24 '17 at 09:25
  • 1
    `nodes` variable is not initialized. You are asigning a value to it in `main` method, which is not being called in your test obviously. This probably causes the NullPointerException. To be sure that it is it, you should investigate your stack trace. If anything is unclear, paste the stack trace here. – bart.s Feb 24 '17 at 09:32
  • 2
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – default locale Feb 24 '17 at 10:13

1 Answers1

0

Adding a statement initialising the nodes should get you rid of the exception -

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

Also, would suggest you to try and improve on few points -

  1. Debug the difference between your main method and CheckNumNodes() test method.
  2. Use of getters and setters
Community
  • 1
  • 1
Naman
  • 27,789
  • 26
  • 218
  • 353