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

5

我在测试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());
    }
}

在运行测试时,由于没有有效的令牌,它始终通过拦截器并被拒绝。我的代码已经被简化,无法获得有效的令牌进行测试,因此我真的需要跳过拦截器。
谢谢您的帮助。
2个回答

4

在集成测试中模拟它:

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 已经足够详细,我不觉得需要添加更多信息。


这个答案太棒了!它解决了我的问题。 - 无名小路

0

我会通过在拦截器上使用配置文件来解决这个问题。在你的测试中,你没有使用这个配置文件(bean 未被注入)。在你的生产环境或者任何其他需要它的环境中,你都需要使用这个新的配置文件。

当然,你需要稍微改变一下使用方式。这应该可以工作:

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

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接