Reputation: 87
I just started learning Junit and I just got Null Pointer Exception in my first test.
If I read correctly @Before
annotation means it will be called before each test but looks like it doesn't or something else is wrong with this code. In this code below I get Null Pointer in myList.add()
line.
import org.junit.Before;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class StudentTest {
private List<String> myList;
@Before
public void init(){
myList = new ArrayList<>();
}
@Test
public void size(){
myList.add("TEST");
assertEquals(1, myList.size());
}
}
Upvotes: 2
Views: 3919
Reputation: 11132
The imports (jupiter) indicate you're using Junit5.
In JUnit5 you have to use the @BeforeEach
annotation to indicate steps that have to be execute before each test method.
The @Before
annotation was used in JUnit4.
I haven't tested this, just read the documentation https://junit.org/junit5/docs/current/user-guide/
Upvotes: 5