0

I started learning junits, and i am trying to mock arraylist class, but it is showing me null pointer exception.

here is my code:

public class MyListTest {

    @Mock
    ArrayList<String> al;
    @Test
    public void whenNotUseMockAnnotation_thenCorrect() {

        when(al.add("a")).thenReturn(true); 
        assertTrue(al.add("a"));


    }

}
ANMOL JAIN
  • 43
  • 1
  • 7
  • you need to initialize the mocks. either with `@RunWith(MockitoJUnitRunner.class)` or in `@Before` method – sidgate Apr 14 '20 at 07:39

2 Answers2

2

It's required to "start" Mockito. Actually the @Mock annotation is acting like a decorator, you need to do one of the following:

  1. Annotate the JUnit test with a MockitoJUnitRunner:
@RunWith(MockitoJUnitRunner.class)
public class MyListTest
  1. Enable Mockito programatically by MockitoAnnotations.initMocks(). You can use this one time in a @Before method of JUnit. Example:
@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}
sigur
  • 662
  • 6
  • 21
1

You should run your testclass with this runner @RunWith(org.mockito.junit.MockitoJUnitRunner.class)

CodeScale
  • 3,046
  • 1
  • 12
  • 20
  • Oh thanks it worked. How Runwith helped me to pass this? – ANMOL JAIN Apr 14 '20 at 07:42
  • 2
    You're welcome. You could find your answers here : https://www.javadoc.io/static/org.mockito/mockito-core/3.3.3/org/mockito/junit/MockitoJUnitRunner.html – CodeScale Apr 14 '20 at 07:46