Manu
Manu

Reputation: 145

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?

Upvotes: 0

Views: 170

Answers (1)

Sergii Bishyr
Sergii Bishyr

Reputation: 8641

You have to tell mockito where to inject the created mock. In your case you just have to use @InjectMocks annotation:

public class SomeUseCaseTest {
    @Mock
    MyCoolService service;

    @InjectMocks
    SomeUseCase useCase = new SomeUseCase();

    ....
}

Upvotes: 1

Related Questions