Mockito + JUnit测试返回NullPointerException

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:

“尚未被存根的方法的默认返回值对于布尔型方法为false,对于返回集合或映射的方法为空集合或映射,否则为null。这也适用于when(...)内的方法调用。”

我几乎可以肯定,这也适用于我的问题。但是我找不到解决方案。我已经尝试了将近10个小时。

我也读了一些有关@Autowired和@Before的东西,显然@autowired是在@before之前创建的,这也可以解释我的NPE。

NPE抛出@Test void getPlantSpeciesById,因为foundPlantSpecies为null,plantSpeciesServiceMock.getPlanySpeciesById(1)也是如此。感觉@Before根本没有运行。

打扰一下,如果我错过了一些东西,我现在真的很累,但是我在拼命地寻找解决方案。

这是我的代码:

@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());
}

}