Mijan
Mijan

Reputation: 21

Stubbed class is still functioning like normally called

I have a Class which I am testing and it has a method from another class which I am trying to stub so that it skips what it does and returns a fake object

class Service{
CacheClass cache;
CacheFactory factory;

public String getString(){
cache = factory.create();

...}

The factory create connects to a database and I want to skip this step; My test looks like this

@Before
public void setup(){
cache = mock(CacheClass.class);
factory = mock(CacheFactory.class);
when(factory.create()).thenReturn(cache);
}

@Test
public void testGetString(){
service = new Service();
String s = service.getString();
...}

When I try to run this test. It attempts to connect to the DB but I do not want it to.

What am I doing wrong?

Upvotes: 1

Views: 41

Answers (1)

GhostCat
GhostCat

Reputation: 140525

Here:

service = new Service();

this doesn't magically inject your mocked objects into that instance of Service.

You probably need something like:

service = new Service(mockedCache, mockedFactory);

There is also this annotation:

@InjectMocks
Service service;

that you could use to have mockito do that automatically; but unfortunately, this construct doesn't give you an error when injecting fails. Thus, simple do something like:

Servce underTest;

@Before
public void setup() {
  underTest = new Service(....

Upvotes: 1

Related Questions