【发布时间】:2017-03-09 10:46:06
【问题描述】:
我有一个 Spring Boot REST 应用程序。所有 GET 请求的单元测试都运行良好;但是,POST 请求都返回了
java.lang.AssertionError: Content type not set
这里是控制器:
@RestController
public class ClassificationController {
private IClassificationService classificationService;
@Autowired
public ClassificationController(IClassificationService classificationService) {
this.classificationService = classificationService;
}
@RequestMapping(value="/category", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public CategoryDTO createCategory(@RequestBody final CategoryDTO category) throws MctException {
return classificationService.createCategory(category);
}
我的单元测试是:
@RunWith(MockitoJUnitRunner.class)
public class ClassificationControllerTest {
@Mock
private IClassificationService classificationService;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(new ClassificationController(classificationService)).build();
}
@Test
public void createCategoryTest() throws Exception {
String jsonTask = String.format("{\"id\": \"2\",\"categoryName\": \"Category Name 2\"}");
MvcResult result = mockMvc.perform(post("/category")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(jsonTask))
.andDo(MockMvcResultHandlers.print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(content().string(containsString("\"id\":2")))
.andExpect(content().string(containsString("\"categoryName\":\"Category Name 2\"")))
.andExpect(status().isCreated())
.andReturn();
}
我也尝试过使用 CategoryDTO 对象而不是 String jsonTask,结果相同。
【问题讨论】:
-
您正在使用
MediaType.APPLICATION_JSON_UTF8_VALUE和.contentType(APPLICATION_JSON_UTF8)。你不应该用同样的吗? -
实际上,它是... one 是我在玩选项时定义的常量。我只是在粘贴代码时忘记将其更改回来。我会在上面更新它。
标签: rest unit-testing junit spring-boot