Unit testing a fluent interface with Mockito

I want to mock the DAO interface used in the builder pattern as shown below. However when I run the test below it passes indicating that my mock object is never called. What am I doing wrong?

public class DBContent {
    ...

    public static class Builder {

        DAO dao = new DAO();
        ...

        public Builder callInsert() {
            ...
            long latest = dao.insert();
            ...
        }
    }
    ...
}

@RunWith(MockitoJUnitRunner.class)
public class DBContentTest {

    @Mock
    DAO dao;

    @Test
    public void test() {
        when(dao.insert()).thenReturn(1111L);
        DBContent db = DBContent.db()
                .callInsert()
                .callInsert()
                .callInsert()
                .build();
        verifyZeroInteractions(dao);
    }
}

Answer

Use PowerMockito instead. There you can define that whenever you have a call to a constructor of DAO, return my mocked object instead of returning actual DAO object.
Please refer this to learn how to use PowerMockito.

Leave a Reply

Your email address will not be published. Required fields are marked *