我有一个Spring Boot REST应用程序。所有GET请求的单元测试工作正常;然而,在POST请求所有返回内容类型未设置Junit REST 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对象尝试这样做而不是具有相同结果的字符串jsonTask。
您正在使用'MediaType.APPLICATION_JSON_UTF8_VALUE'和'.contentType(APPLICATION_JSON_UTF8)'。你不应该使用相同的吗? –
其实,它是......我在玩选项时是一个定义的常量。当我粘贴代码时,我忘了将其改回。我会在上面更新它。 –