Currently I am trying create 10 mock objects of the same class for a test using Mockito in Java;
@Mock Bird bird1;
@Mock Bird bird2;
...
@Mock Bird bird10;
and I try to put these mock objects in a list since I will need to access them in a for loop to write their when-thenReturns
and some other stuff like assigning all of these birds a name. However, when I try to do this it gives me a NullPointerException
. It kind of makes sense that it gives that error, however I desperately try to find a way around for this and access these 10 mocks from some kind of a list or iterable. Is that possible?
Edit: Since @dawood-ibn-karem @pedro-luiz @tgdavies has asked for some more code, let me give it.
protected ArrayList<Bird> birds = new ArrayList<>();
@Test
public void testBirds() {
// Arrange
birdsListSetter();
for (int i = 0; i < 10; i ) {
String voice= VoiceFixture.newRandomChirp();
when(birds.get(i).getChirp()).thenReturn(voice);
}
}
// there some other stuff after this but the error occurs up here
}
public void birdsListSetter() {
birds.add(bird1);
birds.add(bird2);
birds.add(bird3);
birds.add(bird4);
birds.add(bird5);
birds.add(bird6);
birds.add(bird7);
birds.add(bird8);
birds.add(bird9);
birds.add(bird10);
}
When I run the test, it fails at the first when-thenReturn saying that
NullPointerException: Cannot invoke "Bird.getChirp()" because the return value of "java.util.ArrayList.get(int)" is null
CodePudding user response:
I was basically thinking that adding @Mock was enough for initializing, but apparently I was wrong. Editing the code as
@Mock Bird bird1=mock(Bird.class)
fixed my problem. Thanks to kind helpers!
CodePudding user response:
Even though @saarantras answered that he solved his problem, I wanted to point it out that
@Mock Bird bird1=mock(Bird.class)
Is not the recommended usage @Mock and Mockito.mock().
@Mock
@Mock Bird bird1
Mockito.mock()
Bird bird1=mock(Bird.class)
Mockito.mock() method and @Mock annotation are doing slightly the same, which is defining a mock object in unit tests. However, there are some differences.
I'm not going into those differences, but you can have a look at
Mockito.mock() vs @Mock vs @MockBean
One thing that makes that NullPointerException happen is forgetting to add
@ExtendWith(MockitoExtension.class)
public class BirdTest {
@Mock Bird bird1;
@Mock Bird bird2;
@Mock Bird bird3;
@Mock Bird bird4;
@Mock Bird bird5;
@Mock Bird bird6;
@Mock Bird bird7;
@Mock Bird bird8;
@Mock Bird bird9;
@Mock Bird bird10;
At you test class level, wich isn't required when using Mockito.mock()