看到我的逻辑正在使用SwaggerUI正常工作后,我正在尝试为Spring模块编写一个JUnit测试。
但是,发生的情况是我错过了H2实例中的某些数据(仅用于测试),我不明白为什么。
这就是我在做什么:
MyObjectController.java
@PostMapping("/myobject")
public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
// Save and get id
Integer id = service.save();
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri();
// Run async
service.run(id); // At this stage, id = 1 because the insert completed correctly
// Return id
response.setHeader(HttpHeaders.LOCATION, location.toString());
}
MyObjectService.java
@Async
@Transactional
public void run(Integer id) throws Exception { // As above, id = 1 but this time data is not there!
// Retrieve and run
Optional<MyObject> myObject = myObjectDao.findById(id);
if (!myObject.isPresent()) {
throw new NotFound();
}
...
}
/myobject
端点是使用MockMVC调用的,一旦被调用,它将正确返回预期的ID。
如果我在service.run(Integer id)
的开头放置一个断点,并使用SwaggerUI调用/myobject
,我会发现一切都很好,但是在JUnit中运行时不会发生这种情况。
你们能帮我吗?