title: How to write unit test with mocks when method uses ObjectMapper.writeValueAsString
body: <p>I have a SpringMVC project. The method from my FooController that I want to test is:</p>
  
  <pre><code>@GetMapping("/view/{fooId}")
  public String view(@PathVariable String fooId, Model model) throws FooNotFoundException, JsonProcessingException {
      Foo foo = fooService.getFoo(fooId);
      model.addAttribute("fooId", foo.getId());
      model.addAttribute("foo", new ObjectMapper().writeValueAsString(foo));
      return "foo/view";
  }
  </code></pre>
  
  <p>The test that I've written is:</p>
  
  <pre><code>public class FooControllerTest {
      @Mock
      private Foo mockFoo;
      @Mock
      private FooService mockFooService;
      @InjectMocks
      private FooController controller;
      private MockMvc mockMvc;
  
      @Before
      public void setUp() {
          MockitoAnnotations.initMocks(this);
          mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
      }
  
      @Test
      public void testView() throws Exception {
          String fooId = "fooId";
          when(mockFooService.getFoo(fooId)).thenReturn(mockFoo);
          when(mockFoo.getId()).thenReturn(fooId);
  
          mockMvc.perform(get("/foo/view/" + fooId))
                  .andExpect(status().isOk())
                  .andExpect(model().attribute("fooId", fooId))
                  .andExpect(model().attributeExists("foo"))
                  .andExpect(forwardedUrl("foo/view"));
      }
  
  }
  </code></pre>
  
  <p>This test fails with <code>java.lang.AssertionError: No ModelAndView found</code>. 
  When I debug the test, I see it goes wrong when my <code>mockFoo</code> is given to <code>new ObjectMapper.writeValueAsString()</code>. So I think mocked objects cannot be serialized. How do I work around this, how do I make my test pass?
  <hr>
  What have I tried already:</p>
  
  <ul>
  <li>I commented the line <code>model.addAttribute("foo", new ObjectMapper().writeValueAsString(foo));</code> in FooController, this way the test worked (but not the way I want my method to work)! So now I know this is where it goes wrong. </li>
  <li>I commented the line <code>.andExpect(model().attributeExists("foo"))</code> in FooControllerTest, it still produced the above AssertionError.</li>
  <li>Googling and StackOverflowing, but I could find something usable.</li>
  </ul>