title: Unit Testing with jUnit and Mockito for External REST API calls
body: <p>I am building unit tests in a Spring Boot Java application for a service class.  </p>
  
  <p>The service class makes an external call to a REST API service that return a JSON response.  I am mocking this call using Mockito.  I am hardcoding a JSON in the mockserver response.</p>
  
  <p>Is this bad practice to have hardcoded JSONs in your unit tests?  If the JSON structure changes, then the test should fail is my reasoning.  Is there a better, best practice where to do this?</p>
  
  <p><strong>Example Snippet below:</strong></p>
  
  <p><em>The actual code is functional, I just edited this snippet it for brevity to get the idea across, so post a comment if you see any errors:</em></p>
  
  <pre><code>    public class UserServiceTest extends TestCase {
  
      private static final String MOCK_URL = "baseUrl";
      private static final String DEFAULT_USER_ID = "353";
  
      UserService classUnderTest;
      ResponseEntity&lt;Customer&gt; mockResponseEntity;
      MockRestServiceServer mockServer;
      @Mock
      RestTemplate mockRestTemplate;
  
      public void setUp() throws Exception {
          super.setUp();
  
          classUnderTest = new UserRestService();
          mockRestTemplate = new RestTemplate();
          mockServer = MockRestServiceServer.createServer(mockRestTemplate);
  
          ReflectionTestUtils.setField(classUnderTest, "restTemplate",
                  mockRestTemplate);
          ReflectionTestUtils.setField(classUnderTest, "userSvcUrl",
                  MOCK_URL);
      }
  
      public void testGetUserById() throws Exception {
  
          mockServer.expect(requestTo(MOCK_URL + "/Users/" + DEFAULT_USER_ID)).andExpect(method(HttpMethod.GET))
                  .andRespond(withSuccess(
                          "{\n" +
                                  "    \"UserCredentials\": {\n" +
                                  "        \"Password\": \"\",\n" +
                                  "        \"PasswordNeedsUpdate\": false,\n" +
                                  "        \"Security\": [\n" +
                                  "            {\n" +
                                  "                \"Answer\": \"\",\n" +
                                  "                \"Question\": \"Why did the bicycle fall over?\"\n" +
                                  "            }\n" +
                                  "        ]\n" +
                                  "}"
                          , MediaType.APPLICATION_JSON));
  
  
          Customer customer = classUnderTest.getUserById(DEFAULT_USER_ID);
  
          mockServer.verify();
          assertNotNull(customer);
          assertEquals(DEFAULT_USER_ID, customer.getId());
      }
  }
  </code></pre>