NoSuchField error in java code but field exists

179 Views Asked by At

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.

1

There are 1 best solutions below

1
On

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
 }
 }