When you need to test the models' functions in your project, you would use the class DBSpec
as a super class of your JUnit test like this:
public class MovieSpec extends DBSpec {
@Test
public void shouldValidateMovieAttributes() {
Movie movie = new Movie();
the(movie).shouldNotBe("valid");
movie.set("title", "blah", "year", "1122");
the(movie).shouldBe("valid");
}
@Test
public void shouldStoreDirectorAndMovies() {
Person director = new Person("Stephen Spielberg");
director.saveIt();
director.add(new Movie("Saving private Ryan", 1998));
director.add(new Movie("Jaws", 1982));
a(Movie.count()).shouldBeEqual(2);
List<Movie> movies = director.getAll(Movie.class).orderBy("year");
the(movies.get(0).getTitle()).shouldBeEqual("Jaws");
the(movies.get(1).getTitle()).shouldBeEqual("Saving private Ryan");
}
}
A lot of things are happening here. The super class DBSpec
will do the following automatically:
Before test executes:
- opens a connection
- starts a new transaction on the DB connection
After test executes:
- rolls back DB transaction (deletes, inserts updates)
- closes DB connection
This way, you only write code that is related to your business logic, and not worry about opening/closing connections.
Also, because DBSpec
rollbacks your transactions, your test database is always in a clean state. For a full example of a project that shows how this works, please refer to: https://github.com/javalite/simple-example