【问题标题】:Is there a way to verify that a method on Spring Controller was called using Mockito有没有办法验证使用 Mockito 调用了 Spring Controller 上的方法
【发布时间】:2016-07-08 04:33:16
【问题描述】:

这是我的 Mockito 测试:

@RunWith(MockitoJUnitRunner.class)
public class Controller_Test {

    private MockMvc mockMvc;

    @InjectMocks
    private EmployeeController employeeController;

    @Mock
    private InputValidationService inputValidationService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(restController).build();

    }

    @Test
    public void testGetEmployeeDetails() {

        EmployeeController spy = Mockito.spy(employeeController);
        MvcResult result = mockMvc.perform(get("/employee/details/9816")).andDo(print()).andExpect(status().isOk()).andReturn();

    // Have some basic asserts here on the result that are working fine


    }


    }

现在我的问题是,有没有办法断言我期望在我的控制器中调用的方法实际上被调用了。

我知道它是,但是我如何通过单元测试来断言它

例如 这是我在控制器中的 RequestMapping:

@RequestMapping(value = "/employee/details/{id}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
    @ResponseStatus( HttpStatus.OK)
    @ResponseBody   
    public EmployeeDetails getEmployeeDetailsById(@PathVariable String employeeID) {

    //Some business logic

    }

现在我想做一些断言,比如:

Mockito.verify(spy, times(1)).getEmployeeDetailsById();

所以基本上我想断言我期望被调用的方法就是被调用的方法。我知道这可以在我拥有的模拟服务对象上完成,即 inputValidationService 但也希望控制器也有类似的东西。

如果您希望我发布任何其他详细信息,请告诉我。

【问题讨论】:

  • 这不是 MockMvc 的用途。您应该验证(匹配)响应。
  • @SotiriosDelimanolis 我明白了,我也有关于响应的断言。但我有多个映射返回相同的结果。就像我说的那样,我有其他断言可以看到我期望被调用的方法正在被调用,但我想知道是否有一种方法可以断言 Mockito 直接调用了正确的映射。我不关心应该如何使用 MockMvc,这就像一个技术上可能与否的问题。

标签: java spring unit-testing junit mockito


【解决方案1】:

也许晚了,但我发现 org.springframework.test.web.servlet.result.HandlerResultMatchers 可以验证正在调用正确的控制器和方法。例如:

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.handler;

    mockMvc
        .perform(get("/employee/details/9816"))
        .andExpect(handler().handlerType(EmployeeController.class))
        .andExpect(handler().methodName("getEmployeeDetailsById"));

【讨论】:

    【解决方案2】:

    您可以使用@MockBean。这将使用 Mockito bean,您可以使用标准 Mockito 函数,如“验证”。

    http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-mocking-beans

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      相关资源
      最近更新 更多