【问题标题】:Spring MVC Unit Testing - Mocked Service method is not calledSpring MVC 单元测试 - 未调用模拟服务方法
【发布时间】:2021-03-29 10:25:59
【问题描述】:

我正在做一个 Spring Boot 项目,我有一个控制器,它调用一个服务方法并处理输出。

我正在使用 spring MockMvc 来测试 web 层。在我的测试类中,我使用 Mockito.when() 模拟了服务方法。但是当我调用相应的处理方法时,它并没有调用模拟的服务方法,而是返回一个空响应。

控制器

@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 = []

请帮我解决这个问题。 提前致谢!

【问题讨论】:

    标签: spring-boot mockito spring-boot-test mockmvc spring-mvc-test


    【解决方案1】:

    您错误地存根googleAuth.getAuthURL

    您在测试中创建并在存根期间使用的MockHttpServletRequest 与通过MockMvc 发送的HttpServletRequest 实例不同。此外,它们彼此不相等(使用Object.equals,因为它没有被覆盖)

    默认情况下,Mockito 使用 equals 来验证存根中的参数是否与实际调用中的参数匹配。您的存根参数与调用参数不匹配,因此返回方法的默认值 (null)。

    最简单的解决方法是放松参数匹配器。

    Mockito.when(googleAuth.getAuthURL(
                     any(HttpServletRequest.class), 
                     eq("free")))
           .thenReturn("www.google.com");
    

    【讨论】:

      猜你喜欢
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多