对我的RestController的简单测试失败了。
设置 - 具有以下依赖项的SpringBoot 2.0.0.BUILD-SNAPSHOT:
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-web')
runtime('org.springframework.boot:spring-boot-devtools')
runtime('com.h2database:h2')
compileOnly('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
城市对象:
@Getter
@Setter
@NoArgsConstructor
public class City {
private Long id;
private String city;
public City(Long id, String city) {
this.id = id;
this.city = city;
}
}
控制器类:
@RestController
@RequestMapping("/cities")
public class CityController {
@GetMapping
public List<City> findAllCities() {
return Collections.singletonList(new City(1L, "Rancho Cordova"));
}
}
CityControllerTest类:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CityController.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class CityControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void testGetAllCities() throws Exception {
mockMvc.perform(get("/cities")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
我运行Test时得到的异常:
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.Collections$SingletonList
我错过了什么????????
答案 0 :(得分:0)
我的坏。我上面提到的错误是我为Controller提供了参数。相反,代码应该是这样的:
@SpringBootTest(classes = CityApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)