2

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);
    }
}
user3139545
  • 6,882
  • 13
  • 44
  • 87
  • 4
    You create a mock DAO in your test, but the builder that you test doesn't use it. It creates its own DAO. You need to pass the mock DAO as argument when constructing the builder. Learn about dependency injection. – JB Nizet Jun 13 '15 at 21:54

1 Answers1

1

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.

Dhaval
  • 1,046
  • 6
  • 10