I am building unit tests in a Spring Boot Java application for a service class.
The service class makes an external call to the REST API service, which returns a JSON response. I mock this call using Mockito. I am hard-coded JSON in a mockserver answer.
Is this bad practice having hardcoded JSON in your unit tests? If the JSON structure changes, then the test should fail, these are my considerations. Is there a best, best practice where to do this?
Example snippet below:
The actual code is functional, I just edited this snippet for brevity to get this idea, so post a comment if you see any errors:
public class UserServiceTest extends TestCase { private static final String MOCK_URL = "baseUrl"; private static final String DEFAULT_USER_ID = "353"; UserService classUnderTest; ResponseEntity<Customer> 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()); } }
source share