【发布时间】:2022-01-17 18:10:18
【问题描述】:
我正在尝试测试基于 Spring Boot 的休息端点。代码能够返回预期的输出,但测试失败并出现以下错误:
已解决 [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class java.util.LinkedList] with preset Content-Type 'null']
对此的任何想法将不胜感激!
这是相同的代码:
控制器->
@RestController
public class SampleController {
@Autowired
StudentService studentService;
@GetMapping(value="students",produces = "application/json")
public ResponseEntity<List<Student>> getStudentDetails(){
return new ResponseEntity<List<Student>>(studentService.getAllStudents(),HttpStatus.OK);
}
}
服务类->
@Service
public class StudentService {
private List<Student> listOfStudents;
@PostConstruct
public void init() {
List<Student> list1= new LinkedList<Student>();
Student s1 = new Student("a","S1");
list1.add(s1);
listOfStudents = list1;
}
public List<Student> getAllStudents(){
return listOfStudents;
}
}
波乔->
public class Student {
private String sectionName;
private String name;
public String getRollNum() {
return sectionName;
}
public void setRollNum(String rollNum) {
this.sectionName = rollNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String rollNum, String name) {
this.sectionName = rollNum;
this.name = name;
}
@Override
public String toString() {
return "Student [sectionName=" + sectionName + ", name=" + name + "]";
}
}
测试->
@SpringBootTest(classes = {SampleController.class,StudentService.class})
@AutoConfigureMockMvc
public class SampleControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
SampleController sampleController;
@MockBean
StudentService studentService;
@Test
public void getAllUsersTest() throws Exception{
List<Student> mockedList = new LinkedList<Student>();
Student dummyStudent = new Student("dummy","Dummy Student");
mockedList.add(dummyStudent);
Mockito.when(studentService.getAllStudents()).thenReturn(mockedList);
mockMvc.perform(get("/students")).andExpect(status().isOk());
}
}
【问题讨论】:
标签: spring-boot-test