【问题标题】:How to test Spring REST webservice when using a HandlerInterceptorAdapter?使用 HandlerInterceptorAdapter 时如何测试 Spring REST Web 服务?
【发布时间】:2019-05-29 19:06:20
【问题描述】:

我正在开发一个 Spring Web 服务。我想测试我的端点,但由于某种原因,我在运行测试时总是遇到以下异常:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.....IncomingInterceptor' 

但是,我用@Component 注释了这个类。当我使用外部客户端测试端点时,拦截器工作!有人知道如何解决这个问题吗?

这是我测试端点时的代码: 私有 MockMvc mockMvc;

@InjectMocks
private AccountController accountController;

@Mock
private IncomingInterceptor incomingInterceptor;

private Gson gson;

@Before
public void setup() {
    gson = new Gson();
    mockMvc = MockMvcBuilders.standaloneSetup(accountController).addInterceptors(incomingInterceptor).build();
}

@Test
public void testAddAccount() throws 
    mockMvc.perform(MockMvcRequestBuilders.post("/account/add")
            .content(gson.toJson(account))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNotEmpty());
}

IncomingInterceptor 的代码:

@Component
public class IncomingInterceptor extends HandlerInterceptorAdapter {

@Autowired
private Gson gson;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//code in here works
    return true;
}
}

注意:我不想测试拦截器是否工作,我想测试端点!!! 提前致谢!

【问题讨论】:

    标签: spring testing interceptor


    【解决方案1】:

    虽然您的测试代码 sn-ps 没有显示使用的测试运行器 (@RunWith(...)),但我猜您使用的是 SpringRunnerSpringJUnit4ClassRunner 测试运行器。

    您的 sn-p 模拟了 IncomingInterceptor 的一个实例,但是它没有作为 bean 添加到 (test)ApplicationContext 中。使用 @MockBean 而不是 @Mock 将您的模拟 bean 添加到 ApplicationContext

    @MockBean
    private IncomingInterceptor incomingInterceptor;
    

    【讨论】:

    • 我正在使用 Spring Runner --> @RunWith(SpringRunner.class)
    猜你喜欢
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2010-09-17
    相关资源
    最近更新 更多