How to unit test CRUD operations

I like to unit test CRUD (Create, Read, Update, Delete) operations for my domain objects as well as find all. I use the same template again and again, it’s quick to do and makes sure that the basic operations work. Here is what I do :

* A first find all to get all the objects from the database
* Create an object with random values and persist it into the database
* Find the created object from the database
* Make sure it exists
* Make sure it has the right random values
* Update the created object with other random values into the database
* Find the updated object from the database
* Make sure it still exists
* Make sure it has the new random values
* A second find all makes sure that there is one more object in the database
* Delete the object from the database
* Find the object from the database
* Make sure it doesn’t exist
* A third find all makes sure that there is the initial number of objects in the database

Here is the (simplified) JUnit code that tests the CRUD operations for an Item.

@Test
public void testCRUD() throws Exception {

    // Gets two random numbers
    Long random = getRandom();
    Long updateRandom = getRandom();

    // Item is the domain object
    Item item = new Item();

    // The method findAll brings back all the objects from the DB
    int firstFindAll = findAll();

    // Item gets mock values and is persisted. Id is returned
    item = getMockItemValues(item, random);
    persist(item);
    Long id = item.getId();

    // Find the created object with the given Id and makes sure it has the right values
    item = find(id);
    assertNotNull("Object should exist", item);
    checkMockItemValues(item, random);

    // Updates the object with new random values
    item = getMockItemValues(item, updateRandom);
    merge(item);

    // Find the updated object and makes sure it has the new values
    item = em.find(Item.class, id);
    assertNotNull("Object should exist", item);
    checkMockItemValues(item, updateRandom);

    // Gets all the objects from the database...
    int secondFindAll = findAll();

    // ...and makes sure there is one more object
    if (firstFindAll + 1 != secondFindAll) fail("The collection size should have increased by 1");

    // The object is now deleted
    remove(item);

    // Find the object and make sure it has been removed
    item = em.find(Item.class, id);
    assertNull("Object should not exist", item);

    // Gets all the objects from the database...
    int thirdFindAll = findAll();

    // ...and makes sure we have the original size
    if (firstFindAll != thirdFindAll) fail("The collection size should have be the same as original");
}

If you have any other ideas, let me know.

One thought on “How to unit test CRUD operations

  1. I was searching for best practices in crud testing to improve my actual aproach, which its exactly the same as yours :P, ¿more coincidences? my name is also Antonio :D,

Leave a Reply