我有一个弹簧休息控制器,它可以触发应用程序事件
@RestController
public class VehicleController {
@Autowired
private VehicleService service;
@Autowired
private ApplicationEventPublisher eventPublisher;
@RequestMapping(value = "/public/rest/vehicle/add", method = RequestMethod.POST)
public void addVehicle(@RequestBody @Valid Vehicle vehicle){
service.add(vehicle);
eventPublisher.publishEvent(new VehicleAddedEvent(vehicle));
}
}
我有一个控制器的集成测试,类似于
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = VehicleController.class,includeFilters = @ComponentScan.Filter(classes = EnableWebSecurity.class))
@Import(WebSecurityConfig.class)
public class VehicleControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private VehicleService vehicleService;
@Test
public void addVehicle() throws Exception {
Vehicle vehicle=new Vehicle();
vehicle.setMake("ABC");
ObjectMapper mapper=new ObjectMapper();
String s = mapper.writeValueAsString(vehicle);
given(vehicleService.add(vehicle)).willReturn(1);
mockMvc.perform(post("/public/rest/vehicle/add").contentType(
MediaType.APPLICATION_JSON).content(s))
.andExpect(status().isOk());
}
}
现在,如果我删除事件发布行,测试成功。但是,对于该事件,它会遇到错误。
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: null source
我尝试了很多不同的东西,以避免或跳过测试中的行,但没有任何帮助。你能告诉我测试此类代码的正确方法是什么吗?提前致谢
我已经在本地重现了这个问题和这个异常......
org.springframework.web.util.NestedServletException: 请求处理失败;嵌套异常是 java.lang.IllegalArgumentException: null source
。强烈暗示VehicleAddedEvent
的构造函数如下所示:
public VehicleAddedEvent(Vehicle vehicle) {
super(null);
}
如果你进一步查看堆栈跟踪,你可能会看到类似这样的内容:
Caused by: java.lang.IllegalArgumentException: null source
at java.util.EventObject.<init>(EventObject.java:56)
at org.springframework.context.ApplicationEvent.<init>(ApplicationEvent.java:42)
所以,在回答你的问题时;问题不在于你的测试,而在于VehicleAddedEvent
构造函数中的超级调用,如果你更新它,即调用super(vehicle)
而不是super(null)
,那么事件发布不会引发异常。
这将允许你的测试完成,尽管你的测试中没有任何内容断言或验证此事件是否已发布,因此你可能想要为此添加一些内容。您可能已经实现了ApplicationListener<Vehicle>
(如果没有,那么我不确定发布"车辆事件"有什么好处),因此您可以将其@Autowire
VehicleControllerTest
并验证车辆事件是否像这样发布:
// provide some public accessor which allows a caller to ask your custom
// application listener whether it has received a specific event
Assert.assertTrue(applicationListener.received(vehicle));