0

I am trying to unit test catch block to convert List into Json format using jackson. Here is my code:

   public String convert(List<POJO> list) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            data = objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException exception) {
            System.out.println("Exception message: {}", exception.getMessage());
        }
        return data;
    }

I tried unit testing this way:

@Mock
ObjectMapper mockObjectMapper;

@Test(expected = JsonProcessingException.class)
public void doThrowException() throws JsonProcessingException {
    doThrow(JsonProcessingException.class).when(mockObjectMapper).writeValueAsString(any());
    dataTransformer.convert(new ArrayList<>());
    verify(mockObjectMapper.writeValueAsString(any()));
}

I have been trying to get my head around to cover this unit test for full coverage. I looked up couple of articles on SO, but no luck. Since I am new to unit testing world, I have a feeling that I am definitely missing something here.

1
  • You cannot mock objectmapper as you are creating a new instance in the method. It needs to be passed in/injected Commented May 21, 2019 at 16:05

1 Answer 1

1

1) Your test logic is not correct in respect of the implementation. In the implementation you catch the exception, so in the exception test case you will never get it as expected.

2) As said in the comment, you cannot mock ObjectMapper if the dependency is not visible from the client code of the class. Here it doesn't have any way to mock the class. You could add a constructor or a setter for setting that, but well does it make sense ?

3) Indeed you should not mock here. Your component under test maps some list elements to a String. You don't want to mock but test the mapping logic both in the exception cases and in the nominal cases. Otherwise your test will not have a great value.
To get the JsonProcessingException you could inspire from the excellent answers of this post.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, I understand. But how do I test the exception in that case. I am not sure what kind of input will generate JsonProcessingExcetion. Any pointers?
I think I fixed the problem of coverage by throwing the JsonProcessingException.
How did you achieve that ? I updated to answer to your first comment.
Instead of catching the exception, I am throwing the exception now. Only thing here is that I have to throw exception in all the methods that call this method. This way the unit test coverage is 100%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.