How to deal with such test case?

Discussions

General J2EE: How to deal with such test case?

  1. How to deal with such test case? (3 messages)

    Hi,All
     There is a question about test case puzzle me, it is the test involved insert and delete data. How do you guys deal with this situation, use Mock objects or there are some methods, which have insert(), delete() method, and there is a big test case, which invoke the insert() method first, and invoke the delete method last. or any solution else?
     Any tips or repies will be appreciated!

    Thanks.
    Jeff.Yu

    Threaded Messages (3)

  2. Typical Problem[ Go to top ]

    Hi Jeff, the situation you describe is a typical situation when testing database based applications. Here is what I normally do:

    public void testDbStuff() throws Exception {

       Connection connection = null;
       try{
          connection = openConnection();
          connection.setAutoCommit(false);
          //in a method if I need it again in a later test case.
          doInsertStuff();

       } finally {
          if(connection != null){
             connection.rollback(); //deletes all inserts and updates and deletes etc. done during test.
             connection.close();
          }
       }
    }


    Notice how the transaction is rolled back in the finally clause. That way you don't have to worry about what updates you made in the database during the test. It is all deleted and set back, after the test. The nice thing about that is, that if your database contains other test data, for instance for playing around with when testing the UI, these test data will NOT be erased or changed by the test.

    Sometimes I create the connection and call setAutoCommit(false) in the setUp() method of the test class, and call connection.rollback(); and connection.close(); in the tearDown() method. However, I have experienced that if an exception is thrown from the test method, the tearDown method is not always called. So, usually I use the try-finally method.
  3. Typical Problem[ Go to top ]

    Thanks for jakob's reply, it was really a good solution.
  4. Hi,All
      Now, i got another question is: how often should i run this sort of test case, becasue it involved database, this kind of test case is time consuming. Do i need to run them all the time, Or just several times a day. because i will have many this kind of test case as my project grows, it will be a time consuming work. What do you think of it.

    Thanks
    Jeff.Yu