I'm trying to use setUp to initialise an array of objects in JUnit for my test methods but I'm doing something wrong as the tests throw up errors (null pointer exception). They run fine when I initialise arrays in the test methods themselves but this obviously isn't ideal. Can anyone point out what I'm doing wrong here?
class MainTest {
Lord baratheons[];
Lord starks[];
//Setup & Teardown
@Before
static void setUp() throws Exception {
Lord baratheons[] = new Lord[3];
baratheons[0] = new Lord("Robert", 15);
baratheons[1] = new Lord("Renly", -5);
baratheons[2] = new Lord("Stannis", 30);
System.out.println("Baratheons initialised!");
Lord starks[] = new Lord[3];
starks[0] = new Lord("Robb", -60);
starks[1] = new Lord("Eddard", 0);
starks[2] = new Lord("Jon", 90);
System.out.println("Starks initialised!");
}
//Tests
@Test
void testGratefulLord() {
// Lord baratheons[] = new Lord[3];
// baratheons[0] = new Lord("Robert", 15);
int x = baratheons[0].getRelationship();
baratheons[0].giveFief();
assertEquals(baratheons[0].getRelationship(), (x+=10));
}
EDIT:
N.B In addition to following the steps outlined in the below solutions, I'd like to note for posterity that I was also using the wrong tag for the setup. As this is JUnit 5, the tag is @BeforeEach. @Before is the tag for JUnit 4, which was why the setup method wasn't being called. I hope this is helpful to future users.
baratheons = new Lord[3];and it should workLord[] baratheonsinsteadsetUp()? This prevents theint x = baratheons[0].getRelationship();to fail to resolvebaratheonto a variable.baratheons = new Lord[3];andstarks = new Lord[3];inside setUp()staticfromsetUpmethod.