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 !
You stubbed googleAuth.getAuthURL incorrectly.
The MockHttpServletRequest you create in your test and use during stubbing is not the same instance as HttpServletRequest that is sent via MockMvc. Also, they are not equal to each other (Object.equals is used as it is not overriden)
By default Mockito uses equals to verify if arguments in a stubbing match those in the real call. Your stubbing params do not match call params, thus a default value for the method (null) is returned.
The simplest way to fix is to relax argument matchers.
Mockito.when(googleAuth.getAuthURL(
any(HttpServletRequest.class),
eq("free")))
.thenReturn("www.google.com");