简体   繁体   中英

How do I write a unit test for a controller class that has a Post method?

public class ReportEmailController {
    
             @ApiImplicitParam(name = "Authorization", value = "JWT Token", required = true, dataType = "string", paramType = "header", example = Constants.SAMPLE_JWT_TOKEN)
                    @ApiOperation(value = "Details reporter email-service ", notes = "This method shows you thats sending summary id email info.")
                    @PostMapping(value = "/id/email-info", produces = "application/json")
                    public ResponseEntity<EmailInfoIdResponse> idEmailInfo(
                            @Valid @RequestHeader(value = "companyId", required = true) @ApiIgnore String companyId,
                            @Valid @RequestHeader(value = "user", required = true) @ApiIgnore String user,
                            @RequestBody IdEmailInfoRequest request) {
                
                        request.setCompanyId(companyId);
                        request.setAuthUser(user);
                        log.info("New ID Email Info Report request:{}", request);
                
                        List<EmailInfoIdParams> responseInfo = this.reporterService.getIdEmailInfo(request);
                        EmailInfoIdResponse response = new EmailInfoIdResponse();
                        response.setEmailInfoIdParams(responseInfo);
                        response.setStatus("SUCCESS");
                        response.setStatusCode(202);
                        response.setStatusDescription("SUCCESS");
                        return ResponseEntity.accepted().body(response);
                    }
}
            
@RunWith(MockitoJUnitRunner.class)            
public class ReportEmailControllerTest  {
            
            @InjectMocks
                private ReporterService reporterService;
            
                @Mock
                private EmailInfoRepository emailInfoRepository;
            
                @InjectMocks
                private ReportEmailController reportEmailController = new ReportEmailController();
            
                @Test
                public void testIdEmailInfo_whenRequestIsValidReturnValidList() {
                
                        getIdEmailInfoRequest();
                
                        List<EmailInfo> emailInfoList = new ArrayList<>();
                        EmailInfo emailInfo = new EmailInfo();
                        emailInfo.setMessage("test");
                        emailInfoList.add(emailInfo);
                        when(emailInfoRepository.findIdEmailInfos(idEmailInfoRequest)).thenReturn(emailInfoList);
                        log.info("emailInfoList:", emailInfoList);
                        ResponseEntity<EmailInfoIdResponse> response = reportEmailController.idEmailInfo("1","user,",idEmailInfoRequest);
                        assertNotEquals(response.getBody().getEmailInfoIdParams().size(),0);
            }
}

My controller class and test class are as above. When I run this test, I get a NullPointerException error on the following lines in the test and controller class, but I do not expect this error to return. Could it be a problem with the definitions, can you please help, I couldn't solve it in any way.

-> Test class : ResponseEntity response = reportEmailController.idEmailInfo("1","user,",idEmailInfoRequest);

-> Controller class : List responseInfo = this.reporterService.getIdEmailInfo(request);

While unit testing controller, I would suggest you use Webclient . Also I see you are trying to test both the service as well as the controller in one go, which should not be done, you should unit test only one thing at a time.

As far as NPE go,

@InjectMocks
private ReporterService reporterService;

I believe it should be,

@Mock
private ReporterService reporterService;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM