Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing in web applications that use databases

I am building a web application that uses the database for Users, Security/roles, and to store content.

It seems a little daunting to me to begin on the road of unit testing because I have to make sure my database has been initialized properly for my tests to run.

What are common practices to help in this regard?

i.e. while developing/testing, I might delete a user, but for my test to pass that user has to be in the database, along with his profile, security settings etc.

I know I can create a setup script, something to recreat the databas etc.

I don't want to end up spending my entire time maintaining my tests and ensuring my database is in sych

Or is that the cost of Unit Testing/TDD?

like image 446
Blankman Avatar asked Dec 04 '08 15:12

Blankman


People also ask

Can unit tests use databases?

To test an application it is not enough to use unit tests. You must also perform functional testing and regression testing. Database access falls outside the scope of unit testing, so you would not write unit tests that include database access.

Should unit tests connect to database?

Unit tests shouldn't depend on infrastructure 🔗There's no way to test this function without a database connection available at the time of testing. If a new developer clones the project they will need to set up a database before they can successfully run the unit tests.

Which type of testing will include database?

Functional testing validates that users and applications can access and update data in the database. Some testers prefer to validate database functionality by testing the application or applications that rely on the database.


2 Answers

The solution is Mocking. Mocks "replace" the connection. The unit under test will "connect" to the Mock and executes its statement. The Mock returns normal resultsets o.s.e.

After the test, the mock can give you a list of all methods, that were called by the unit under test. Easymock.org

As the other said: DB connection aren't a unit test. So drop it and do it local with Mocking objects

like image 167
guerda Avatar answered Nov 22 '22 22:11

guerda


It's not a unit test if you are testing more than one unit.

Usually you'll have one component (your page, or the business layer) talking to a data layer object that is responsible for actually connecting and querying the database. My recommendation is to develop a unit test for the first component, using dependency injection to pass in a mock version of the DataLayer (which acts on hardcoded data, or a List you pass in, etc). This way you are testing your higher level code in isolation from the other components.

Then you are free to develop other unit tests (and integration tests) for the data layer to ensure that it is handling it's job (writing to the database) correctly.

like image 34
matt b Avatar answered Nov 22 '22 23:11

matt b