Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have problem testing JsonProcessingException, can someone help me please?

Here is the code I want to test

@GetMapping("/find-something")
    public Something findSomething(@RequestParam String exampleString) throws CustomExceptionWeb, JsonProcessingException {
        CustomClass customClass = objectMapper.readValue(exampleString, CustomClass.class);
        return serviceWeb.findBy(customClass);
    }

Here is the test method :

private static final String BASE_URL = "/sample/api/example/find-something";

@Autowired
    private MockMvc mvc;

 @MockBean
    private ObjectMapper objectMapper;

@Test
void expectToThrowWhenParamIsInvalid() throws Exception {
final String ueryParams = "?customFakeName=\"\"name\":\"fakeItTillYouMakeIt\:\"desc\"\"\n";


when(objectMapper.readValue(anyString(), eq(CustomClas.class))).thenThrow(JsonProcessingException.class);
        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(BASE_URL + ueryParams);

        try {
            mvc.perform(requestBuilder);
            fail();
        } catch (NestedServletException e) {
            System.out.println("Testing = " + e.getRootCause());
            assertTrue(e.getRootCause() instanceof JsonProcessingException);
        }
}


JsonProcessingException it's printing error :

com.fasterxml.jackson.core.JsonProcessingException: N/A


I'm trying to send invalid json string so when objectMapper start mapping string to class throw JsonProcessingException error.

Tnx.

What I have tried:

I tried almoast everything.

When I'm testing
RuntimeException
, test is ok...
Posted
Updated 21-Aug-21 10:40am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900