【问题标题】:Integration testing and spring application events集成测试和 Spring 应用程序事件
【发布时间】:2017-12-21 01:41:53
【问题描述】:

我有一个触发 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

我尝试了很多不同的方法,以避免或跳过测试中的行,但没有任何帮助。您能否告诉我测试此类代码的正确方法是什么?在此先感谢

【问题讨论】:

  • 是否可以看到完整的堆栈跟踪?

标签: spring junit mockito integration-testing


【解决方案1】:

我已经在本地重现了这个问题和这个异常......

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 java.lang.IllegalArgumentException: null source

... strong> 暗示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&lt;Vehicle&gt;(如果没有,那么我不确定发布“车辆事件”有什么好处),因此您可以将@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));

【讨论】:

  • 我没有明确传递 null;但是,当您指出我看到我传递的参数实际上变为 null 时。所以,为什么它是 null 是另一回事,但它可以工作。谢谢。
猜你喜欢
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 2021-02-09
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
相关资源
最近更新 更多