0

I have the following code.

public  class Table {

    Integer[] data;

    public Table() {
        this.data = new Integer[100];
    }

    public boolean insert(int key){
        data[53] = 1;
         return true;
    }
 }

&& 

public class test{

private Table tab;

protected void setUp() throws Exception {
        tab = new Table();
    }

public void testInsertTable() {
        tab.insert(1);
        assertTrue(tab.data[53] == 1);  // error here
    }
}

The test class is run using JUnit. The code works when i run in it Eclipse but i get a NoSuchField error on the line pointed by the comment when i run it outside of Eclipse.

The class responsible for the problem is Table, that much i know for certain.

user569685
  • 191
  • 1
  • 13
  • As per java doc, the error is thrown, if an application tries to access or modify a specified field of an object, and that object no longer has that field. Check in junit, if you are getting Table correctly. Moreover `Integer[] data;` is a package protected field and not public. So if your test class is in same package, then only it will work – Optional Dec 03 '19 at 18:43

1 Answers1

1

What could be wrong is you are not using @Before annotation on the setup method

The correct code should be

public class test{

private Table tab;

@Before
 protected void setUp() throws Exception {
       tab = new Table();
  }

@Test
public void testInsertTable() {
        tab.insert(1);
        assertTrue(tab.data[53] == 1);  // error here
 }
 } 
Parth Manaktala
  • 1,112
  • 9
  • 27