Problem is with the this line where you are mocking the call to objectmapper.

Mockito.when((objMapper).readValue(“”,ConfigDetail.class)).thenReturn(configDetail);

Correct syntax is

Mockito.when(objMapper.readValue(“”,ConfigDetail.class)).thenReturn(configDetail);

Notice the bracket position. When using Spy or Verify, the bracket position is diff. then when using when-then syntax.

Answer from lrathod on Stack Overflow
🌐
Stack Exchange
softwareengineering.stackexchange.com › questions › 416379 › should-i-mock-objectmapper-in-my-unit-tests
java - Should I mock ObjectMapper in my unit tests? - Software Engineering Stack Exchange
JSON is like a peripheral to your application, ObjectMapper should only be present at boundaries of your system. You can test these boundaries (without mocking ObjectMapper) by passing them JSON input, and asserting that the POJO output is correct.
Discussions

Avoid mocking the ObjectMapper!
Why on earth would anyone do that anyway? More on reddit.com
🌐 r/java
104
42
November 11, 2023
java - Mockito multiple ObjectMapper values - Stack Overflow
Target target1 = new Target(); ... eq(Target.class))).thenReturn(target1); Mockito.when(mapper.convertValue(anyMap(), eq(Target.class))).thenReturn(target2); The actual code is called this way , where i want to mock the objectmapper to return target1 or target2 depending on the ... More on stackoverflow.com
🌐 stackoverflow.com
August 19, 2020
java - How to correctly mock an ObjectMapper object - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
java - How to mock ObjectMapper with mokito? - Stack Overflow
I'm having trouble with mocking an ObjectMapper bean with mokito. My class containing the ObjectMapper : public class ServiceParent{ @Autowired protected ObjectMapper objectMapper; ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Baeldung
baeldung.com › home › json › jackson › mocking the objectmapper readvalue() method
Mocking the ObjectMapper readValue() Method | Baeldung
January 8, 2024 - Let’s start by setting up our test class. We can easily mock an ObjectMapper and pass it as a constructor argument to our FlowerStringValidator class:
🌐
Red-green-coding
red-green-coding.github.io › bettertests › 2023 › 10 › 16 › testing_objectmapper_mock.html
Avoid mocking the ObjectMapper! | red green coding – blog
October 16, 2023 - In this short article, we’ll show why you shouldn’t mock an ObjectMapper in your tests. We assume you have a general understanding of Java, Unit testing, and Mocking with Mockito. Here is a tutorial to refresh your knowledge about the annotations used in our code samples · A recurring ...
🌐
Roy Tutorials
roytuts.com › home › junit › mock objectmapper.readvalue() using junit mockito
Mock ObjectMapper.readValue() using Junit Mockito - Roy Tutorials
December 4, 2019 - When we write Junit test cases or classes, we generally do not test on real object that are injected into the class that has to be tested using Junit to avoid any test case failure at some point, instead we want to test the business logic out of the written code. We will mock the ObjectMapper class ...
🌐
Reddit
reddit.com › r/java › avoid mocking the objectmapper!
r/java on Reddit: Avoid mocking the ObjectMapper!
November 11, 2023 - So essentially, I've tried both, and for me, mocking the object mapper is objectively better than not mocking it. Until I see evidence that not mocking it is a better plan, I'll continue to advocate for mocking 3rd party dependencies. ... The point of the test is not to verify that the ObjectMapper works correctly, but that you are using it correctly.
Find elsewhere
🌐
Tabnine
tabnine.com › home page › code › java › org.mockito.matchers
org.mockito.Matchers.anyMap java code examples | Tabnine
when(parametersUtils.getTaskInput(anyMap(), any(Workflow.class), any(TaskDef.class), anyString())) .thenReturn(dynamicTasksInput); when(objectMapper.convertValue(anyMap(),any(TypeReference.class))).thenReturn(Arrays.asList(wt2, wt3)); ... taskInput.put("dynamicTaskName", "DynoTask"); when(parametersUtils.getTaskInput(anyMap(), any(Workflow.class), any(TaskDef.class), anyString())).thenReturn(taskInput); ... private <T> ParseCloudCodeController mockParseCloudCodeControllerWithResponse(final T result) { ParseCloudCodeController controller = mock(ParseCloudCodeController.class); when(controller.callFunctionInBackground(anyString(), anyMap(), anyString())) .thenReturn(Task.forResult(result)); return controller; } }
🌐
GitHub
github.com › ArpNetworking › commons › blob › master › src › test › java › com › arpnetworking › commons › jackson › databind › ObjectMapperFactoryTest.java
commons/src/test/java/com/arpnetworking/commons/jackson/databind/ObjectMapperFactoryTest.java at master · ArpNetworking/commons
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; ·
Author   ArpNetworking
🌐
ConcretePage
concretepage.com › questions › 1077
Using Mockito when() in JUnit Test
private ObjectMapper mapper; @Mock · private JsonNode jsonNode; @InjectMocks · private CustomerService customerService; @BeforeEach · void setUp() { MockitoAnnotations.openMocks(this); } @Test · void testGetCustomerDetails() throws Exception { User user = new User(); user.setAge(25); when(userService.getUserResponse(100)).thenReturn(user); when(jsonNode.get("payload")).thenReturn(jsonNode); when(mapper.convertValue(jsonNode.get("payload"), User.class)).thenReturn(user); when(itemService.getItem(100)).thenReturn(new Item()); String result = customerService.getCustomerDetails(100); assertEquals("success", result); } } SIMILAR POSTS ·
🌐
Medium
codefarm0.medium.com › why-did-my-mock-fail-a-spring-boot-testing-gotcha-you-should-know-about-052ed7d1ba17
Why Did My Mock Fail? A Spring Boot Testing Gotcha You Should Know About | by Arvind Kumar | Medium
June 6, 2025 - A convert() method using convertValue() and a toJson() method using writeValueAsString(). ... @ExtendWith(MockitoExtension.class) class MyServiceTest { @Mock ObjectMapper objectMapper; MyService myService; @BeforeEach void setup() { myService ...
🌐
Red-green-coding
red-green-coding.github.io › bettertests › 2023 › 11 › 08 › testing_objectmapper_constructor.html
Avoid mocking the ObjectMapper! (part 2) | red green coding – blog
November 8, 2023 - The root cause here is the design choice to put the ObjectMapper as a parameter into the constructor of our class. In consequence, our test also needs to know which mapper implementation the production code uses so it can construct the test subject.
Top answer
1 of 1
1

I don't see the reason behind writing a test which mocks Object Mapper to throw some exception and then test whether the exception was thrown or not. Instead the test should be for the custom logic which is developed by you. If you have a method like this -

public void publicMethod(messageDto dto)  {
    try{
        privateMethod(dto, param, "other string");
    } catch(JsonProcessingException e){
       // do stuff
       dto.setXXX("XXX"); // The test should be testing this
    }
}

So, the test should be testing whether the dto is set correctly.

@Test
public void shouldFailJsonParsing() throws JsonProcessingException {
        // Given
        final Dto dto = new Dto();

        // When
        when(mapper.writeValueAsString(any()))
                .thenThrow(JsonProcessingException.class);

        // Invoke the method to be tested
        classToBeTestedActor.publicMethod(dto);

        // Test whether expected mock methods are invoked
        verify(mapper, times(1)).writeValueAsString(any());
        verifyNoMoreInteractions(mapper);

        // Assert results
        Assert.assertEquals("XXX", dto.getXXX());
    }

I get your point and I kind of agree with that. I just want to understand why, even if I am forcing the mapper to throw that exception, I am unable to assert it

I think the reason for this is that the exception is catched by you. That is the reason, that exception isn't propagated to your test.

public void publicMethod(messageDto dto) throws JsonProcessingException {
        try{
            privateMethod(dto, param, "other string");
        } catch(JsonProcessingException e){
           // do stuff
        }
    }

Try changing this to -

public void publicMethod(messageDto dto) throws JsonProcessingException {
        privateMethod(dto, param, "other string");
        
    }
🌐
Java Tips
javatips.net › api › lubang-menggali-master › test › ApplicationTest.java
ApplicationTest.java example
*/ @Before public void setContext() { Http.Context.current.set(new Http.Context( 0L, mock(RequestHeader.class), mock(Http.Request.class), new HashMap <String, String>(), new HashMap<String, String>(), new HashMap<String, Object>())); } @Test public void testIndexTemplate() { Content html = views.html.index.render(0, 0); assertThat(contentType(html)).isEqualTo("text/html"); assertThat(contentAsString(html)) .contains("There are 0 game(s) and 0 pending player(s) online."); } private static <T> T readPojo(MockWebSocketWrapper socket, Class<T> clazz) throws InterruptedException, JsonProcessingExce
🌐
LinkedIn
linkedin.com › pulse › json-based-unit-testing-java-albertas-laurinavičius
JSON based Unit testing in Java
July 13, 2022 - After setting up JSON view in IntelliJ debugger , it is very easy to dump objects after stopping at breakpoint and save them separately with intention to use later to load mock data: when(someConverter.findPersonsByEmails(new HashSet<>( Arrays.asList("albertas.laurinavicius@devbridge.com")))) .thenReturn(objectMapper.readValue(SomeClassToTest.class .getResourceAsStream( "/test-resources/someConverterResult.json"), new TypeReference<Map<String, PersonEmail>>() { }));
🌐
Medium
evonsdesigns.medium.com › objectmapper-unit-testing-configured-mapper-features-33e9bec0312e
ObjectMapper: Unit Testing configured Mapper Features | by Joe Evans | Medium
March 12, 2019 - To test the addition of MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, we need to grab the DeserializationConfig from the ObjectMapper.
🌐
Tech with Maddy
techwithmaddy.com › testing-with-spring-boot
Testing with Spring Boot
May 27, 2023 - @Test public void shouldSaveCustomer() throws Exception { Customer customer = new Customer(); customer.setFirstName("firstName"); customer.setLastName("lastName"); customer.setEmail("email@test.com"); customer.setPhoneNumber("0123456789"); mockMvc.perform(post("/customer/save") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(customer))) .andExpect(status().isOk()); }