【发布时间】:2017-06-07 05:59:09
【问题描述】:
我已经设置了一个 Spring Boot 应用程序来使用 Spring MVC 控制器来返回一个项目列表。我有一个 spring 测试,它创建了一个连接到控制器的模拟依赖项,控制器将预期的模拟项列表作为 JSON 数组返回。
我试图简单地断言内容是正确的。我想断言 JSON 数组包含预期的列表。我认为尝试将 JSON 数组解释为 java.util.List 时存在问题。有没有办法做到这一点?
第一个和第二个.andExpect() 通过,但是hasItems() 检查没有通过。我该怎么做才能传入我的List<T> 并验证它是否包含在 JSON 中?我能想到的替代方法是将 JSON 转换为我的 List<T> 并使用“常规 java junit 断言”进行验证
public class StudentControllerTest extends AbstractControllerTest {
@Mock
private StudentRepository mStudentRepository;
@InjectMocks
private StudentController mStudentController;
private List<Student> mStudentList;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
setUp(mStudentController);
// mock the student repository to provide a list of 3 students.
mStudentList = new ArrayList<>();
mStudentList.add(new Student("Egon Spengler", new Date(), "111-22-3333"));
mStudentList.add(new Student("Peter Venkman", new Date(), "111-22-3334"));
mStudentList.add(new Student("Raymond Stantz", new Date(), "111-22-3336"));
mStudentList.add(new Student("Winston Zeddemore", new Date(), "111-22-3337"));
when(mStudentRepository.getAllStudents()).thenReturn(mStudentList);
}
@Test
public void listStudents() throws Exception {
MvcResult result =
mockMvc.perform(get("/students/list"))
.andDo(print())
.andExpect(jsonPath("$", hasSize(mStudentList.size())))
.andExpect(jsonPath("$.[*].name", hasItems("Peter Venkman", "Egon Spengler", "Raymond Stantz", "Winston Zeddemore")))
// doesn't work
.andExpect(jsonPath("$.[*]", hasItems(mStudentList.toArray())))
// doesn't work
.andExpect(jsonPath("$.[*]", hasItems(mStudentList.get(0))))
.andExpect(status().isOk())
.andReturn();
String content = result.getResponse().getContentAsString();
}
}
【问题讨论】:
标签: java json spring spring-mvc spring-test