nirvair
nirvair

Reputation: 4180

unit testing in spring boot giving error when exception thrown in service

So, I have this unit test that I need to run.

@MockBean
private AppServiceImpl appService;


@Test
public void shouldThrowExceptionWhenAppIdIsNull() throws Exception {
    File inputFile = this.getJsonFile();
    RequestDto requestDto = objectMapper.readValue(inputFile.getAbsoluteFile(),
            RequestDto.class);
    AppData appData = requestDto.getAppData();
    appData.setAppId(null);
    requestDto.setAppData(appData);
    when(appService.getUrl(requestDto, "header")).thenThrow(new RequestNotValidException());
    String payload = objectMapper.writeValueAsString(requestDto);
    this.mockMvc.perform(post(Base_URL + "app/requesturl")
            .contentType(contentType).content(payload).header(this.Header, "header"))
            .andExpect(status().is4xxClientError());
}

Interface for service:

SO when I run this test, it throws an exception and doesn't actually assert the test here.

I have added @ResponseStatus(HttpStatus.BAD_REQUEST) on top of RequestNotValidException and it extends RunTimeException

And in the second test case, I get empty response. I tried this API vis Postman and I get the response. Everything works fine there.

@Test
public void getCardRegistration() throws Exception {
    File inputFile = this.getJsonFile();
    RequestDto requestDto = objectMapper.readValue(inputFile.getAbsoluteFile(), RequestDto.class);
    ResponseDto responseDto = new ResponseDto();
    responseDto.setURL(AuthUtils.randomStringToken(35));
    given(appService.getRegistrationUrl(requestDto, "header")).willReturn(responseDto);
    String payload = objectMapper.writeValueAsString(requestDto);
    MvcResult mvcResult = this.mockMvc.perform(post(Base_URL + "app/requesturl")
            .contentType(contentType).content(payload).header(this.Header, "header"))
            .andReturn();
    String contentAsString = mvcResult.getResponse().getContentAsString();
}

Controller content:

    @Autowired
    IAppService appService;

    @RequestMapping(value = "/app/requesturl", method = RequestMethod.POST)
public ResponseDto getCardsRegistration(@RequestBody @Valid RequestDto requestDto, @RequestHeader(value="X-App-Name", required = true) String header) throws RequestNotValidException, JsonProcessingException {
    log.info("Request received in controller: "+ mapper.writeValueAsString(cardRegistrationRequestDto));
    log.info("Header value: "+ header);

    return this.appService.getRegistrationUrl(requestDto, header);
}

Test Class:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AppRestControllerTest {

    protected String Base_URL = "/app";

    protected String Header = "X-App-Name";

    protected MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(),
            Charset.forName("utf8"));

    @Autowired
    protected MockMvc mockMvc;

    protected ObjectMapper objectMapper = new ObjectMapper();

    @MockBean
    private AppServiceImpl appService;

    @Mock
    private AppRegistrationRepository appRegistrationRepository;


        @Before
    public void setUp() throws Exception {
        MapperFacade mapperFacade = new DefaultMapperFactory.Builder().build().getMapperFacade();
        appService = new AppServiceImpl(appRegistrationRepository, mapperFacade);
    }

What did I miss here?

Upvotes: 1

Views: 1086

Answers (1)

Pospolita Nikita
Pospolita Nikita

Reputation: 665

Try to use

@RunWith(SpringRunner.class)
@WebMvcTest(YourController.class)
public class AppRestControllerTest {

Or

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class AppRestControllerTest {

In your tests

Upvotes: 1

Related Questions