Unit testing, a better way

I’ve already blogged about unit testing with Spring and Hibernate. But it turned out that unit testing is much simpler when it is done the right way.

See for yourself and compare.

Instead of having a test Spring context, I manualy wire the beans in the unit test. Instead of executing against the database, I build a fake (mock?) database… a HashMap. No useless work here (that’s what I try, at least…).

As all the code accessing the database is encapsulated in Accessors (DAOs, if you’d preffer), I can just write a new one for testing, which accesses the HashMap database with an annonymous class. And then, just wire the accessor into the class to be tested:

protected void setUp() throws Exception {
  super.setUp();
  accessor = new UserAccessor() {
    private Map<String, User> users = new HashMap<String, User>();
    public void save(User user) {
      if (users.get(user.getName()) == null) {
        users.put(user.getName(), user);
      } else {
        throw new RuntimeException("Already exists: "
          + user.getName());
      }
    }
    public User findByName(String userName) {
      return users.get(userName);
    }
    public boolean exists(String userName) {
      return findByName(userName) != null;
    }
  };
  classUnderTest.setUserAccessor(accessor);
}

Now I can test whatever I want without a database (which means much faster!).

However, I’ve got the feeling that there should be an even better way. Any takers?


  1. Mars

    why not use an in-memory db like HSQLDB for testing?
    is it too slow 4 your tests?
    or do you explicitly not want to use any db for testing the service layer?

  2. Didn’t think of it at the time🙂.

    In the worst case (non portable SQL), one would need to re-implement the database access logic… which is exactly what I did.

    So, yes… an in-memory database would be a better option (specially combined with dbunit).

  3. Joe Fisher

    Look into mockito. In general, your service will call some dao method that will return a collection of things. In mockito, allow the dao to just return what whatever collection you want. Mockito eliminates mist of the boiler plate/impl work you have to do.






%d bloggers like this: