Home > Blockchain >  Null Pointer Exception on 2d array [duplicate]
Null Pointer Exception on 2d array [duplicate]

Time:09-25

I am practicing some Junit testing and I can't get this test to work.

class AssignmentJunitTest {
    
    private AssignmentJunitCorrect beta;

    @Test
    void testMaxCorrect() {
        int[][] a = {{1,3,5},{2,6,10}};
        
        assertEquals(10, beta.max(a));
        fail("not max value");
    }
}

the code this is trying to test is,

public class AssignmentJunitCorrect {

  public int max(int x[][]){
       int m=x[0][0];
       for (int i=0;i<x.length;i  ) {
           for(int j=0;j<x[i].length;j  ) {
               if(m<x[i][j])
                   m=x[i][j];
           }
       }
       return m;
   }
}

whenever I run the Junit test I get a null pointer exception on assertEquals(10, beta.max(a)); what is going wrong here? or am I just approaching all of this wrong?

CodePudding user response:

You need to instantiate AssignmentJunitCorrect class so that you can test it. Assuming it has a no-args constructor you can do the following:

class AssignmentJunitTest {
    
    private AssignmentJunitCorrect beta = new AssignmentJunitCorrect();

    @Test
    void testMaxCorrect() {
        int[][] a = {{1,3,5},{2,6,10}};
        
        assertEquals(10, beta.max(a));
        fail("not max value");
    }
}

CodePudding user response:

Just initialize the object and it's preferable to use @before annotation to put your configuration and creation of the object. the Setup method will be called before each test case

This is the code for Junit 4

class AssignmentJunitTest {
    
    private AssignmentJunitCorrect beta;

    @before
    public void setUp() {
        beta = new AssignmentJunitCorrect();
    }

    @Test
    void testMaxCorrect() {
        int[][] a = {{1,3,5},{2,6,10}};
        
        assertEquals(10, beta.max(a));
        fail("not max value");
    }
}

, And for Junit 5

class AssignmentJunitTest {
    
    private AssignmentJunitCorrect beta;

    @BeforeEach
    public void setUp() {
        beta = new AssignmentJunitCorrect();
    }

    @Test
    void testMaxCorrect() {
        int[][] a = {{1,3,5},{2,6,10}};
        
        assertEquals(10, beta.max(a));
        fail("not max value");
    }
}
  • Related