簡體   English   中英

集成測試和spring應用程序事件

[英]Integration testing and spring application events

我有一個彈簧控制器,它可以激活一個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

我嘗試了很多不同的東西,以避免或跳過測試中的線,但沒有任何幫助。 你能否告訴我測試這些代碼的正確方法是什么? 提前致謝

我已在本地復制此問題,此異常......

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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM