0

I'd like to mock some DB inserts and reads, IE, not do them to my actual production DB, but either create a mock, or do a temporary in memory type of thing, to be able to unit test some methods getting back fake data.

How do I do this in activejdbc?

Coder
  • 1,917
  • 3
  • 17
  • 33
dessalines
  • 6,352
  • 5
  • 42
  • 59

1 Answers1

1

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

ipolevoy
  • 5,432
  • 2
  • 31
  • 46