Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test my services without affecting my database?

I'm writing some integration tests for my application in Spring.I want to test some services however they may call some Data Access Objects and new data will be saved in my DB.I have two alternatives to clear every thing in database after testing is complete:

  1. Use a temp Database to insert test data there
  2. clear all my tables everytime I do a test

however i'm looking for let's say a clean and forward way, so that I can use my database without manual cleaning. Any ideas?

like image 638
user1948609 Avatar asked Dec 04 '25 17:12

user1948609


1 Answers

If you are using Spring framework then I think you should have already checked Spring's reference on how to do testing.

You'll see that Spring will make it so simple for you, in a way that you don't need to interact with transactions directly.Adding a @Transactionl annotation at top of your tests is all you need to do, So what's the benefit of making a test transactional? yes! As mentioned earlier by other answers it will let you rollback your transactions so nothing will remain in your DB. Take a look at this sample code:
    @Transactional
    public class FictitiousTransactionalTest {

        @Before
        public void setUpTestDataWithinTransaction() {
            // set up test data within the transaction
        }

        @Test
        @Rollback(true)
        public void modifyDatabaseWithinTransaction() {
            // logic which uses the test data and modifies database state
        }
    }

Something important to note is that your database must be InnoDB, So if you are using mySQL which is myISAM by default consider altering your tables beforehand.

like image 74
ye9ane Avatar answered Dec 06 '25 07:12

ye9ane