我試圖找到用於測試彈簧啓動應用程序的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:觸發器調用發生在我可以嘲笑任何東西之前?
編寫單元測試不是集成測試。只是實例化'HandlerInterceptor',創建模擬並注入它們。 –
在這種情況下,如何在我的攔截器中模擬'@ autowired'依賴關係?我需要特殊的Spring引導註釋,'@ SpringBootTest'正在完成這項工作。 – Aphax