I am trying to Mock classes but i keep getting a NPE. I've seen this post Mockito - NullpointerException when stubbing Method. In this post they explain this:
"The default return value of methods you haven't stubbed yet is false for boolean methods, an empty collection or map for methods returning collections or maps and null otherwise. This also applies to method calls within when(...)."
I am almost certain that this applies to my problem as well. But i can not find a solution for it. I've been trying for almost 10 hours right now.
Also i read something about @Autowired and @Before, apparently @autowired is created before @before, this could also explain my NPE.
The NPE is thrown at the @Test void getPlantSpeciesById, because foundPlantSpecies is null and so is plantSpeciesServiceMock.getPlanySpeciesById(1). It feels like @Before is not run at all.
Excuse me, if i am missing something, i am really tired at the moment but i am desperately searching for a solution.
Here is my Code:
@SpringBootTest(classes = PlantSpeciesService.class)
@Import({TestConfig.class})
@RunWith(MockitoJUnitRunner.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class PlantSpeciesServiceTest {
@MockBean
private PlantSpeciesRepository plantSpeciesRepository;
@MockBean
private ModelMapper modelMapper;
@Autowired
private PlantSpeciesService plantSpeciesServiceMock;
@Before("com.oopa.domain.services.PlantSpeciesService")
public void setup() {
MockitoAnnotations.initMocks(this);
PlantSpecies tulip = new PlantSpecies();
tulip.setId(1);
tulip.setMinHumidity(200);
tulip.setMaxHumidity(400);
tulip.setName("Tulip");
Mockito.when(plantSpeciesRepository.findById(tulip.getId())).thenReturn(
Optional.of(this.modelMapper.map(tulip, com.oopa.dataAccess.model.PlantSpecies.class))
);
}
@Test
void getPlantSpeciesById() {
PlantSpecies foundPlantSpecies = plantSpeciesServiceMock.getPlantSpeciesById(1);
System.out.println(plantSpeciesServiceMock.getPlantSpeciesById(1));
System.out.println(foundPlantSpecies);
System.out.println();
assertEquals("Tulip", foundPlantSpecies.getName());
}
}