假设我有一些FooInterceptor
:
public class FooInterceptor extends HandlerInterceptorAdapter {
// ...
}
在上下文中配置的:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="my.package.FooInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
我正在为某个控制器创建集成测试:
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "/context.xml")
@ActiveProfiles("test")
public class SomeControllerIT {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
}
...
}
我试图通过创建自定义配置来模拟它:
@Configuration
static class Config {
@Bean
@Primary
public FooInterceptor getFooInterceptor() {
return mock(FooInterceptor.class);
}
}
但在我看来它不起作用。实际的
FooInterceptor
仍然产生并参与测试。如何恰当地模仿它?
最佳答案
所以我继续写了一些代码来解决同样的问题。在我们的测试用例项目中,我们可以通过显式定义我们自己的拦截器来模拟拦截器,这个拦截器扩展了handlerInterceptorAdapter,它将具有模拟原始拦截器的模拟逻辑
public class MockTenantInterceptor extends HandlerInterceptorAdapter
我们可以在不自动连接的情况下初始化模拟拦截器类,并继续在testconfiguration类中注册它。请确保我们有两个配置类,一个用于webconfig,另一个用于testconfig,以添加防止调用生产拦截器的spring配置文件注释。
@Profile("test")
@TestConfiguration
@EnableJpaAuditing
public class TestConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
MockTenantInterceptor mockTenantInterceptor = new MockTenantInterceptor();
registry.addInterceptor(mockTenantInterceptor);
}
}