Mockito 103

testing  mockito  performance 

Tras leer Mockito102 veo el concepto, utilizado la reflexión se hace la mágia para hacer que se devuelva del elemento mockeado la respuesta que queremos para nuestro test, pero… no hay otra manera más estilo ‘Mockito’? Parece innecesariamente complicado hacer reflexión haciendo set del mock.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    private MyController myController;

    @Before
    public void setup(){
        myController = new myController();
    }

    @Test
    public void myControllerTest() throws Exception {
        MyService myService = mock(MyService.class);

        when(myService.getSomethingList().thenReturn(Collections.emptyList());

        ReflectionTestUtils.setField(myController, "myService", myService);

        List<Something> result = myController.getSomethingList();

        Assert.assertTrue(result.isEmpty());
    }

La verdad que sí, haciendo uso de la anotación @InjectMock podemos lograr testear nuestra clase sin utilizar ReflectionTestUtils y haciendo que se devuelva dentro del controller lo que queremos que vuelva del service. El código resultante es mucho más comprensible.

Nuestro código quedaría de la siguiente manera:

1
2
3
4
5
6
7
8
9
10
11
12
13
    @InjectMock
    private MyController myController;

    @Test
    public void myControllerTest() throws Exception {
        MyService myService = mock(MyService.class);

        when(myService.getSomethingList().thenReturn(Collections.emptyList());

        List<Something> result = myController.getSomethingList();

        Assert.assertTrue(result.isEmpty());
    }

Lecturas

http://www.springboottutorial.com/spring-boot-unit-testing-and-mocking-with-mockito-and-junit