我正在进行一个spring-boot项目,其中有一个控制器,它调用一个服务方法并处理输出。
我正在使用springMockMvc来测试web层。在我的测试类中,我用Mockito.when((模拟了服务方法。但当我调用相应的处理程序方法时,它并没有调用模拟的服务方法,而是返回一个null响应。
控制器
@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);
}
}
测试类
@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");
}
返回的响应是
MockHttpServletResponse:
Status = 302
Error message = null
Headers = [Content-Language:"en", Location:"null"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
请帮我解决这个问题。提前感谢!
您错误地截断了googleAuth.getAuthURL
。
您在测试中创建并在存根期间使用的MockHttpServletRequest
与通过MockMvc
发送的HttpServletRequest
实例不同。此外,它们彼此不相等(使用Object.equals
,因为它没有被覆盖(
默认情况下,Mockito使用equals来验证存根中的参数是否与实际调用中的参数匹配。您的存根参数与调用参数不匹配,因此返回该方法的默认值(null(。
最简单的修复方法是放松参数匹配器。
Mockito.when(googleAuth.getAuthURL(
any(HttpServletRequest.class),
eq("free")))
.thenReturn("www.google.com");