NullPointerException in Junit 5 @MockBean

The mocks need to be initialized before they can be used. There are several options to do this.

The first option would be to use @SpringExtension which will initialize the mocks annotated with @MockBean:

@ExtendWith(SpringExtension.class)
public class CompteServiceImplTest {
    @Autowired
    private CompteService CompteService;

    @MockBean
    private compteRepository compteRepository;

    // ...
}

This will make sure that the repository bean is mocked before the service bean is autowired.

However, since you are writing a unit test for the service, you don’t need the Spring extension at all. The second option is to use @Mock instead of @MockBean, and call @InjectMocks in conjunction with the MockitoExtension for constructing the service under test:

@ExtendWith(MockitoExtension.class)
public class CompteServiceImplTest {
    @InjectMocks
    private CompteService CompteService;
    @Mock
    private compteRepository compteRepository;

    // ...
}

Alternatively, you could just call MockitoAnnotations.initMocks(), which will initialize the mocks annotated with @Mock, and use constructor injection for your service:

public class CompteServiceImplTest {
    private CompteService CompteService;

    @Mock
    private compteRepository compteRepository;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.initMocks(this);
        CompteService = new CompteServiceImpl(compteRepository, ...);
    }

    // ...
}

Finally, you could do it all without annotations just by calling Mockito.mock() directly:

public class CompteServiceImplTest {
    private compteRepository compteRepository;

    @BeforeEach
    void setUp() {
        compteRepository = Mockito.mock();
        CompteService = new CompteServiceImpl(compteRepository, ...);
    }

    // ...
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top