Unit testing a fluent interface with Mockito

995 views Asked by At

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);
    }
}
1

There are 1 answers

0
Dhaval On BEST 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.