繁体   English   中英

如何避免在 Spring Boot 集成测试中使用拦截器

[英]How to avoid using an interceptor in Spring boot integration tests

我在测试 REST 请求时遇到问题。 在我的应用程序中,我有一个拦截器,可以在允许请求之前检查令牌有效性。 但是对于我的集成测试,我想绕过检查。 换句话说,我想要么分流拦截器,要么模拟它以始终返回 true。

这是我的简化代码:

@Component
public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String token = request.getHeader("Authorization");
        if (token != null) {
            return true;
        } else {
            return false;
        }
    }
}


@Configuration
public class RequestInterceptorAppConfig implements WebMvcConfigurer {
    @Autowired
    RequestInterceptor requestInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(requestInterceptor).addPathPatterns("/**");
    }

}

和测试:

@SpringBootTest(classes = AppjhipsterApp.class)
@AutoConfigureMockMvc
@WithMockUser
public class DocumentResourceIT {

    @Autowired
    private DocumentRepository documentRepository;

    @Autowired
    private MockMvc restDocumentMockMvc;

    private Document document;

    public static Document createEntity() {
        Document document = new Document()
            .nom(DEFAULT_NOM)
            .emplacement(DEFAULT_EMPLACEMENT)
            .typeDocument(DEFAULT_TYPE_DOCUMENT);
        return document;
    }

    @BeforeEach
    public void initTest() {
        document = createEntity();
    }

    @Test
    @Transactional
    public void createDocument() throws Exception {
        int databaseSizeBeforeCreate = documentRepository.findAll().size();
        // Create the Document
        restDocumentMockMvc.perform(post("/api/documents")
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(document)))
            .andExpect(status().isCreated());
    }
}

运行测试时,它总是通过拦截器并被拒绝,因为我没有有效的令牌。 我这里的代码被简化了,我无法获得有效的测试令牌,所以我真的需要跳过拦截器。

谢谢你的帮助

模拟它(在集成测试中):

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

// non-static imports

@SpringBootTest
// other stuff
class IntegrationTest {
  @MockBean
  RequestInterceptor interceptor;

  // other stuff

  @BeforeEach
  void initTest() {
    when(interceptor.preHandle(any(), any(), any())).thenReturn(true);
    // other stuff
  }

  // tests
}

@BeforeEach 和 @SpringBootTest 做什么,你知道; Mockito 的 any() 只是说“不管参数”; 对于@MockBean 和 Mockito 的 when-then,Javadoc 已经足够好,我觉得不需要添加信息。

我会通过在拦截器上使用配置文件来解决这个问题。 在您的测试中,您不使用配置文件运行(未注入 bean)。 在您的生产中或您需要的任何环境中,您都可以使用新配置文件运行。

当然你需要稍微改变一下用法。 这应该有效:

@Configuration
public class RequestInterceptorAppConfig implements WebMvcConfigurer {
    @Autowired
    Collection<RequestInterceptor> requestInterceptors;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        requestInterceptors.forEach(interceptor -> registry.addInterceptor(interceptor).addPathPatterns("/**");
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM