jeudi 7 juillet 2016

Is there a way to verify that a method on Spring Controller was called using Mockito

This is my Mockito Test:

@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


    }


    }

Now my question is, Is there a way to assert that the method I expected to be called in my controller was actually invoked.

I know it was, but how do I assert it with unit test

For e.g. This is my RequestMapping in the controller:

@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

    }

Now I would like to make some assertion like:

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

So basically I would like to assert that the method I expected to get called was the one that got called. I know this can be done on the Mock Service object that I have i.e. inputValidationService but would like something similar for the controller as well.

Please let me know if there are any additional details that you would like me to post.

Aucun commentaire:

Enregistrer un commentaire