避免控制器初始化测试春天启动的HandlerInterceptor

避免控制器初始化测试春天启动的HandlerInterceptor

问题描述:

我试图找到用于测试弹簧启动应用程序的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

@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 { 
    } 
} 

希望这可以帮助。