Search code examples
springspring-bootjunitjunit4

MockitoJUnitRunner with SpringBoot 3.1.1


having this class:

@Service
@Transactional(readOnly = true)
public class PdfService {
    
    private final AsAPIService asAPIService;

    public PdfService(AsAPIService asAPIService) {
        this.asAPIService = asAPIService;
    }


    public void generatePdf() throws UnirestException {

        asAPIService.chart(AsRequestBody.builder()
                .authKey("6248i23")
                .authPwd("8f1adbf3deaefa8d6a4c05")
                .build());
    }
    

}

I have this test defined:

@RunWith(MockitoJUnitRunner.class)
class PdfServiceTest {

    @InjectMocks
    PdfService pdfService;


    @Test
    void generatePdf() throws UnirestException {
        pdfService.generatePdf();
    }

}

but when I run it I have this error:

java.lang.NullPointerException: Cannot invoke "com.xiocolmenares.service.PdfService.generatePdf()" because "this.pdfService" is null

I also tried:

@ExtendWith(MockitoExtension.class)
class PdfServiceTest {

    @InjectMocks
    PdfService pdfService;


    @Test
    void generatePdf() throws UnirestException {
        pdfService.generatePdf();
    }

}

with the same result


Solution

  • PdfService must have AsAPIService as a field, but your test code doesn't have a mocking object of AsAPIService to inject into the field.

    In @InjectMocks document, if arguments can not be found, then null is passed.

    If you run success, follow below.

    @ExtendWith(MockitoExtension.class)
    class PdfServiceTest {
        @Mock
        AsApiService AsApiService;
    
        @InjectMocks
        PdfService pdfService;
    
    
        @Test
        void generatePdf() throws UnirestException {
            pdfService.generatePdf();
        }
    
    }