mercredi 27 septembre 2017

Mockito failing basic example

I'm new to mockito so I'm trying to learn with some basic examples.

Here is my service.

public class MyCoolServiceImpl implements MyCoolService{

    public String getName() {
        return "String from service";
    }

}

MyCoolService is just an interface

public interface MyCoolService {

    public String getName();
}

And I have a simple use case:

public class SomeUseCase {
    private MyCoolService service = new MyCoolServiceImpl();

    public String getNameFromService(){
        return service.getName();
    }
}

Mothing complicated. So I write my test class as follows:

public class SomeUseCaseTest {
    @Mock
    MyCoolService service;

    SomeUseCase useCase = new SomeUseCase();

    @Before
    public void setUp(){
        initMocks(this);

        when(service.getName()).thenReturn("String from mockito");
    }


    @Test
    public void getNameTest(){

        String str = useCase.getNameFromService();

        assertEquals("String from mockito", str);
    }
}

So, as I understand, str should contains "String from mockito", since I'm telling mockito to return that string when service.getName() is called, however my test fails because it returns "String from service".

What am I missing here? Did I misunderstood how mockito works?

Aucun commentaire:

Enregistrer un commentaire