gpt4 book ai didi

java - 测试 spring boot HandlerInterceptor 时避免 Controller 初始化

转载 作者:行者123 更新时间:2023-12-02 02:42:36 26 4
gpt4 key购买 nike

我正在尝试找到正确的配置来测试Spring-boot应用程序的HandlerInterceptor,具有@MockBean依赖项,但不初始化整个Bean池,因为一些 Controller 具有无法模拟的 @PostConstruct 调用(知道 @Before 调用在 @PostContruct Controller 调用之后进行)。

现在我已经了解了这种语法:

@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:无法加载ApplicationContext,因为一个具有@PostContruct调用的RestController尝试从proprieteService获取数据code> 模拟此时尚未被模拟的人。

所以我的问题是:如何防止 Springboot 测试加载器初始化我的所有 Controller ,其中 1:我不需要测试,2:触发在我可以模拟任何内容之前发生的调用?

最佳答案

@M。 Deinum 向我展示了方法,实际上解决方案是编写真正的单元测试。我担心的是,我需要在我的拦截器中填充这些@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 {
}
}

希望这能有所帮助。

关于java - 测试 spring boot HandlerInterceptor 时避免 Controller 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45191819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com