我正在
Spring Boot
Java应用程序中为服务类构建单元测试.
服务类对返回JSON响应的REST API服务进行外部调用.我正在用Mockito嘲笑这个电话.我在mockserver响应中硬编码JSON.
这是一种不好的做法,在单元测试中使用硬编码的JSON吗?如果JSON结构发生变化,那么测试失败就是我的推理.有没有更好的,最好的做法在哪里这样做?
以下示例代码段:
实际的代码是实用的,我只是编辑了这个片段,为了简洁起见,所以如果您发现任何错误,请发表评论:
public class UserServiceTest extends TestCase {
private static final String MOCK_URL = "baseUrl";
private static final String DEFAULT_USER_ID = "353";
UserService classUnderTest;
ResponseEntity 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());
}
}