WildDev
WildDev

Reputation: 2367

Spring DAO testing

I've heard it's recommended to create separated interfaces for the each DAO classes to make it's test easier. The answer on the question "why?" was about of possibility of substitution the original DAO implementation by test one. But there was no info about how to do that.

So, I'm interested how to do that.

Assuming we've the simple DAO interface:

public interface PersonDao {
    void add();
    ...
}

and the simple as well it's implementation:

@Repository
public class PersonDaoImpl implements PersonDao {

   public void add() {
      // doing something
   }
}

how can we test it like that:

public class PersonDaoTest {

   @Autowire
   FakePersonDao fakePersonDao;

   @Test
   public void addTest() {
      fakePersonDao.add();
   }
}

where's the FakeDao is second "test" implementation of PersonDao interface:

public class FakePersonDaoImpl implements PersonDao {

    public void add() {
        // doing something different
    }
}

hm?

Should we use everywhere @Autowired in combination with @Qualifier or there's a better way?

Upvotes: 0

Views: 360

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96385

When people suggest substituting a mock for a real DAO, they're talking about testing the layer that uses the DAO. So if you have a service layer, the test might look like

public class MyServiceTest {
    private MyServiceImpl objectUnderTest = new MyServiceImpl();
    private PersonDao fakePersonDao;
    @Before
    public void setUp() {
        fakePersonDao = new FakePersonDao(); // or define it using Mockito
        objectUnderTest.setPersonDao(fakePersonDao);
    }
}

This way you can exercise the functionality of the service that needs testing without being dependent on having access to whatever resource the DAO encapsulates.

Upvotes: 1

Related Questions