Testing with database connection
ActiveJDBC Models are easy to test, and there is a convenience class for opening and closing connections during tests.
Test database for testing
It is customary for JavaLite projects to use one database for testing and a different one for running the system locally. It makers it easy to preserve data in place in the "development" database, and still use the full power of database access to your test database during tests.
For example, you could have some user data in a development database which will allow you to log in, and perform other operations, and yet you can run test logic against your test database, destroy and re-create any data in it, without having to wipe clean your development database.
DBSpec for database tests
org.javalite.activejdbc.test.DBSpec is a super-class for tests that require a database connection. It is integrated with database file configuration and will automatically open a corresponding database connection before a test execution and close it after the test.
Please, see more on environments on database file configuration page.
Example of a
Lets say we are developing a blog, and we need to persist a post. A post will have title, content and author. All these attributes are required. Here is an example of a model we are testing:
1 2 3 4 5 6
A test will look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13
Technically speaking, you can use it for any test requiring a connection, but it is also easy to use for Model tests.
Steps of execution
In the test above the
- open a test connection defined in
- start a transaction
- make connection available during tests
- roll back transaction after the test execution to keep the database clean
- close the connection
This class allows for tests to run in a "clean room" environment, since the database tables will always have a clean state for any given test.
Non-models database tests
DBSpec is usually used to test models, it can be used to test any code that require a database connection. If you need to get a hold of that connection, you can use class
How to comment
The comment section below is to discuss documentation on this page.
If you have an issue, or discover bug, please follow instructions on the Support page