Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test "add" in DAO without using "find" etc.?

In following code the issue is, that I cannot test dao.add() without using dao.list().size() and vice versa.

Is this approach normal or incorrect? If incorrect, how can it be improved?

public class ItemDaoTest {

    // dao to test
    @Autowired private ItemDao dao;

    @Test 
    public void testAdd() {
        // issue -> testing ADD but using LIST

        int oldSize = dao.list().size();
        dao.add(new Item("stuff"));
        assertTrue (oldSize < dao.list().size());
    }

    @Test
    public void testFind() {
        // issue -> testing FIND but using ADD

        Item item = new Item("stuff")
        dao.add(item);
        assertEquals(item, dao.find(item.getId()));
    }
}
like image 566
Xorty Avatar asked Mar 30 '12 20:03

Xorty


2 Answers

I think your test are valid integration tests as stated above, but I would use Add to aid in the testing of of Find and vice verse.. At some level you have to allow yourself to place trust in your lowest level of integration to your external dependency. I realize there is a dependency to other methods in your tests, but I find that Add and Find methods are "low level" methods that are very easy to verify. They essentially test each other as they are basically inverse methods.

Add can easily build preconditions for find

Find can verify that an add was successful.

I can't think of a scenario where a failure in either wouldn't be caught by your test

like image 67
TGH Avatar answered Nov 19 '22 00:11

TGH


Your testAdd method has a problem: it depends on the assumption that ItemDao.list functions properly, and yet ItemDao is the Class that you're testing. Unit tests are meant to be independent, so a better approach is use plain JDBC -as @Amir said- to verify if the record was introduced in the database.

If you're using Spring, you can relay on AbstractTransactionalDataSourceSpringContextTests to access JDBCTemplate facilities and assure a rollback after the test was executed.

like image 31
Carlos Gavidia-Calderon Avatar answered Nov 18 '22 23:11

Carlos Gavidia-Calderon