I was working on a spring boot project where I have controller which calls a service method and process the output.
I'am using spring MockMvc for testing the web layer. In my test class I have mocked the service method with Mockito.when(). But when I call the corresponding handler method it is not calling the mocked service method instead returns a null response.
Controller
@Controller
public class SocialLoginEndpoints {
@Autowired
@Qualifier("facebookAuth")
SocialLogin faceBookAuth;
@Autowired
@Qualifier("googleAuth")
SocialLogin googleAuth;
@Autowired SignupService signupService;
@GetMapping("/auth/google")
public String googleAuth(@RequestParam String signupType, HttpServletRequest request) {
return "redirect:" + googleAuth.getAuthURL(request, signupType);
}
}
Test Class
@WebMvcTest(SocialLoginEndpoints.class)
class SocialLoginEndpointsTest {
@Autowired MockMvc mockMvc;
MockHttpServletRequest mockHttpServletRequest;
@MockBean GoogleAuth googleAuth;
@MockBean FacebookAuth facebokAuth;
@MockBean SignupService signupService;
@BeforeEach
void setUp() {
mockHttpServletRequest = new MockHttpServletRequest();
}
@Test
void googleAuth() throws Exception {
Mockito.when(googleAuth.getAuthURL(mockHttpServletRequest, "free"))
.thenReturn("www.google.com");
mockMvc
.perform(MockMvcRequestBuilders.get("/auth/google").param("signupType", "free"))
.andExpect(MockMvcResultMatchers.redirectedUrl("www.google.com"))
.andExpect(MockMvcResultMatchers.status().isFound())
.andDo(MockMvcResultHandlers.print());
Mockito.verify(googleAuth, Mockito.times(1)).getAuthURL(mockHttpServletRequest, "free");
}
The reponse which is returned is
MockHttpServletResponse:
Status = 302
Error message = null
Headers = [Content-Language:"en", Location:"null"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
please help me to resolve this issue. Thanks in Advance !