我正在寻找答案,但我没有找到与我的问题类似的东西。
我有简单的REST API,写作学习项目,我很难在控制器中创建正确的POST方法。其他基本命令工作正常,只是这一点使事情变得艰难。
我的代码:
控制器:
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/v1/foo")
public class TaskController {
private final DbService dbService;
private final FooMapper fooMapper;
@Autowired
public FooController(DbService dbService, FooMapper fooMapper) {
this.dbService = dbService;
this.fooMapper = fooMapper;
}
@RequestMapping(method = RequestMethod.POST, value = "/createFoo", consumes = APPLICATION_JSON_VALUE)
public void createFoo(@RequestBody FooDto fooDto) {
dbService.saveFoo(fooMapper.mapToFoo(FooDto));
}
存储库:
public interface FooRepository extends CrudRepository<Foo, Long> {
@Override
List<Foo> findAll();
Optional<Foo> findByIdEquals(long fooId);
@Override
Foo save(Foo foo);
@Override
long count();
}
服务:
@Service
public class DbService {
@Autowired
private FooRepository repository;
public List<Foo> getAllFoos() {
return repository.findAll();
}
public Foo saveFoo(final Foo foo) {
return repository.save(foo);
}
public Optional<Foo> getFoo(final long fooId) {
return repository.findByIdEquals(fooId);
}
public void deleteFoo (final long FooId) {
repository.deleteById(fooId);
}
}
使用以下代码测试上述代码:
@Test
public void testShouldCreateTask() throws Exception {
//Given
FooDtofookDto = new FooDto(1L, "Title", "Content");
Foo foo = new Foo(1L, "Title after", "Content after");
when(dbService.saveFoo(foo)).thenReturn(foo);
//When&&Then
Gson gson = new Gson();
String jsonContent = gson.toJson(fooDto);
System.out.println(jsonContent);
mockMvc.perform(post("/v1/foo/createFoo")
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(jsonContent))
.andExpect(status().isOk())
.andExpect((jsonPath("$.title", is("Title after"))));
}
给出了这个结果:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /v1/foo/createFoo
Parameters = {}
Headers = {Content-Type=[application/json;charset=UTF-8]}
Body = {"id":1,"title":"Title","content":"Content"}
Session Attrs = {}
Handler:
Type = com.crud.foos.controller.FooController
Method = public void com.crud.foos.controller.FooController.createFoo(java.lang.String,com.crud.foos.domain.FooDto)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: No value at JSON path "$.title"
如果我理解正确处理了POST请求,但由于某种原因,序列化的对象体丢失了,因此我收到了#34;没有值&#34;结果,但状态是200.我正在咨询大量的页面和来源,我无法在提供的代码中找到错误。如果有任何额外信息有帮助,我当然会提供。