我有一个弹簧控制器,可以触发ApplicationEvent
@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
我尝试了很多不同的东西,以避免或跳过测试中的界限,但没有任何帮助。你能否告诉我测试这些代码的正确方法是什么?提前致谢
答案 0 :(得分:7)
我已在本地复制此问题,此例外......
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>
(如果不是,那么我不确定发布&#39;车辆事件的好处是什么),这样您就可以@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));