2017-07-19 101 views
0

我試圖找到用於測試彈簧啓動應用程序的HandlerInterceptor,與@MockBean依賴正確的配置時,但沒有初始化全豆池,因爲有些控制器具有@PostConstruct電話,可不會被嘲笑(知道@Before呼叫在控制器調用@PostContruct之後)。避免控制器初始化測試春天啓動的HandlerInterceptor

現在我已經來到這句法:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(classes = Application.class) 
public class MyHandlerInterceptorTest { 
    @Autowired 
    private RequestMappingHandlerAdapter handlerAdapter; 
    @Autowired 
    private RequestMappingHandlerMapping handlerMapping; 
    @MockBean 
    private ProprieteService proprieteService; 
    @MockBean 
    private AuthentificationToken authentificationToken; 

    @Before 
    public void initMocks(){ 
    given(proprieteService.methodMock(anyString())).willReturn("foo"); 
    } 

    @Test 
    public void testInterceptorOptionRequest() throws Exception { 
    MockHttpServletRequest request = new MockHttpServletRequest(); 
    request.setRequestURI("/some/path"); 
    request.setMethod("OPTIONS"); 

    MockHttpServletResponse response = processPreHandleInterceptors(request); 
    assertEquals(HttpStatus.OK.value(), response.getStatus()); 
    } 
} 

但測試失敗,因爲java.lang.IllegalStateException: Failed to load ApplicationContext一個RestController有@PostContruct呼叫嘗試從proprieteService模仿誰沒有在這個時候嘲笑獲取數據。

所以我的問題是:我如何防止Springboot測試加載程序初始化我的所有控制器,其中1:我不需要測試,2:觸發器調用發生在我可以嘲笑任何東西之前?

+3

編寫單元測試不是集成測試。只是實例化'HandlerInterceptor',創建模擬並注入它們。 –

+0

在這種情況下,如何在我的攔截器中模擬'@ autowired'依賴關係?我需要特殊的Spring引導註釋,'@ SpringBootTest'正在完成這項工作。 – Aphax

回答

1

@M。 Deinum向我展示了方法,的確解決方案是編寫一個真正的單元測試。我擔心的是我需要在我的Intercepter中填充@autowired依賴關係,並且正在尋找一些神奇的註釋。但它是通過簡單的構造,只是編輯自定義WebMvcConfigurerAdapter並通過依賴這樣的:

@Configuration 
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter { 
    AuthentificationToken authentificationToken; 

    @Autowired 
    public CustomWebMvcConfigurerAdapter(AuthentificationToken authentificationToken) { 
    this.authentificationToken = authentificationToken; 
    } 

    @Bean 
    public CustomHandlerInterceptor customHandlerInterceptor() { 
    return new CustomHandlerInterceptor(authentificationToken); 
    } 

    @Override 
    public void addInterceptors(InterceptorRegistry registry) { 
    registry.addInterceptor(customHandlerInterceptor()); 
    } 
} 

而且攔截:

public class CustomHandlerInterceptor implements HandlerInterceptor { 
    private AuthentificationToken authentificationToken; 

    @Autowired 
    public CustomHandlerInterceptor(AuthentificationToken authentificationToken) { 
    this.authentificationToken = authentificationToken; 
    } 

    @Override 
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
    } 
} 

希望這可以幫助。