I'm trying to understand mockito but I'm getting stuck, im trying to mock multiple objects using the @Mock annotation, but it will not mock them. It will only mock the first object (mockBoard). If I mock the BoardFactory myself using mock(Boardfactory.class) it will work. But i dont understand why it wont work in the @Mock?
@ExtendWith(MockitoExtension.class)
class MapParserTest {
//mocks just fine
@Mock private Board mockBoard;
//wont mock both factories, sets them to null
@Mock private BoardFactory mockBoardFactory;
@Mock private LevelFactory mockLevelFactory;
//this will work
//private BoardFactory mockBoardFactory = mock(BoardFactory.class);
private MapParser mapParser = new MapParser(mockLevelFactory, mockBoardFactory);
private List<Ghost> ghosts = new ArrayList<>();
private List<Square> startPositions = new ArrayList<>();
@Test
void testParseCharMatrix() {
//Arrange
char[][] mapMatrix = new char[1][];
mapMatrix[0] = new char[]{'#'};
//nullPointer exception thrown here
when(mockBoardFactory.createBoard(any(Square[][].class))).thenReturn(mockBoard);
//Act
mapParser.parseMap(mapMatrix);
//Assert
verify(mockLevelFactory).createLevel(mockBoard, ghosts, startPositions);
}}
@Mockdoes mock the annotated field. Post a complete minimal example reproducing the problem. Mockign a List doesn't make much sense: why not use a real List? It's trivial to create one, isn't it? And why do you moc mapParser, and then create a non-mock one? That doesn't make sense either.@BeforeEachseems to imply that you are using JUnit 5, but that version does not use@Ruleanymore. If you are using JUnit 5, you would annotate your class with@ExtendWith(MockitoExtension.class). Rules are a part of JUnit 4. Of course, that doesn't explain why the first@Mockworks.