2017-07-16 60 views
4

我有一個彈簧安置控制器,它會觸發了ApplicationEvent集成測試和Spring應用程序事件

@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 

我嘗試一堆不同的東西,以避免或跳過線測試,但沒有任何幫助。您能否告訴我什麼是測試此類代碼的正確方法?在此先感謝

+4

難道是可以看到完整的堆棧跟蹤? –

回答

5

我有本地重現這個問題,這個異常...

org.springframework.web.util.NestedServletException:請求處理失敗;嵌套的例外是java.lang.IllegalArgumentException異常:空源

... 強烈意味着你的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調用,如果你更新,以便爲來電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)); 
+0

我並沒有傳遞null明確;但是,當你指出這一點我看我傳遞參數實際上正變得無效。所以,爲什麼它是空的是另一回事,但它有一個非空值的工作。謝謝。 – Imran

相關問題