mercredi 29 mai 2019

How to test Spring REST webservice when using a HandlerInterceptorAdapter?

I am developing a Spring web service. I want to test my endpoints but for some reason I always get the following exception when I run the tests:

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

However, I annotated the class with @Component. The interceptor works when I test the endpoint using an external client! Does somebody know how to solve this problem?

Here is my code when I test the endpoint: private 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());
}

The code for the 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;
}
}

Note: I do not want to test if the Interceptor works, I want to test the Endpoints!!! Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire