简体   繁体   中英

java.lang.AssertionError when executing unit test when using my own model as parameter

I got a AssertionError when I execute the unit test. response.getBody() is null.

Here is unit test method;

public void when_CustomerNumNotNull_Expect_TspResult() {
   /*
     some code
   */

    TspResultDto tspResultDto = new TspResultDto();

    tspResultDto.setTspResult("blabla");

    Mockito.doReturn(tspResultDto).when(creditService)
        .getTspResult(tspInputDto);

    ResponseEntity<TspResponse> response = creditController
        .getTspResult(TspRequest);

    Assert.assertNotNull(response.getBody()); // error occured this line because body null.
    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
    //Assert.assertEquals(true, response.getBody().isHrResult());
  }

    }

TspInputDto and TspRequest are my model Class. But I don't get an error when I run it with a single parameter like below without needing the model class.

Mockito.doReturn(newCreditApplicationDto).when(creditService)
        .getNewCreditApplicationNo(customerNum);

    ResponseEntity<NewCreditApplicationResponse> response = creditController
        .getNewCreditApplicationNo(customerNum);

    Assert.assertNotNull(response.getBody());
    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

Here is controller;

public ResponseEntity<TspResponse> getTspResult(
      TspRequest tspRequest) {

    TspInputDto tspInputDto = creditDemandRestMapper
        .toTspInputDto(tspRequest);

    TspResultDto tspResultDto = creditService
        .getTspResult(tspInputDto);

    TspResponse tspResponse = creditDemandRestMapper
        .toTspResponse(tspResultDto);

    return new ResponseEntity<>(tspResponse, HttpStatus.OK);

  }

Here is service;

public TspResultDto getTspResult(
      TspInputDto tspInputDto) {

    TspResultDto tspResultDto = new TspResultDto();

    /*
       Some code here...
    */
    return tspResultDto;
  }

Where am I doing wrong?

In this line:

Mockito.doReturn(tspResultDto).when(creditService)
        .getTspResult(tspInputDto);

you set the mock to return your tspResultDto object if the argument equals() to tspInputDto , meaning it should be an equal object (in terms of equals() comparison). Probably your TspInputDto class doesn't have equals method defined properly.

Anyways, I'd propose to rewrite this line of code using argThat matcher:

Mockito.doReturn(tspResultDto).when(creditService)
        .getTspResult(ArgumentMatchers.argThat(tspInputDto ->
            // condition for provided tspInputDto
        ));

Have you mocked the creditController? If you haven't then it will not give you response mock object.

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