我正在尝试找到正确的配置,用于测试具有HandlerInterceptor
依赖项的Spring-boot应用程序的@MockBean
,但是没有初始化整个Bean池,因为某些控制器具有{{1} }无法模拟的调用(知道在调用@PostConstruct
之后调用@Before
)。
现在我已经开始使用这种语法了:
@PostContruct
但是测试失败,@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
有一个@PostContruct调用试图从RestController
模拟中获取此时尚未被嘲笑的数据。
所以我的问题是:如何阻止Springboot测试加载程序初始化我的所有控制器,其中1:我不需要测试,2:在我可以模拟任何东西之前发生的触发调用?
答案 0 :(得分:2)
@M。 Deinum向我展示了方式,确实解决方案是编写一个真正的单元测试。我担心的是我需要填充@autowired
中的Intercepter
个依赖项,并且正在搜索一些神奇的注释。但是编辑自定义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 {
}
}
希望这可以提供帮助。