0

Ive recently entered into the world of mocking using jMock - in particular mocking in regards to db. Ive read some posts on how its not possible to (easily) mock a local object contained in a class / method. As Ive never actually done any proper TDD / mocking, Ive always defined objects such as 'ResulSet' in my methods where appropriate. Therefore my question is, when Im going forward with future DB classes / methods, should I define ResultSet as a field, and then have an appropriate Setter Method as a means to access it for testing?

If I should, is this still reasonable considering I probably wouldnt use this setter method for anything else but testing?

Essentially, am I to define all objects with setter methods to aid mocking?

I saw this post: Mocking methods of local scope objects with Mockito and it seems to suggest what Ive said above is acceptable.

I know it seems like a basic question, but I dont want to form bad habits early on.

Community
  • 1
  • 1
RoshP
  • 151
  • 1
  • 2
  • 9

2 Answers2

3

What you have in the post that you've mentioned is not a good way to go. I suggest starting your TDD adventure without mocking. Start with test-first approach and you will end up with design, which does not require such hideous testing (e.g. partial mocking). Then start mocking, but remember: only mock what you own (so if ResultSet is a JDBC class, you definately should not mock it).

bbankowski
  • 343
  • 1
  • 9
1

You shouldn't be mocking at that level. Basically the idea is that you have interfaces that acts as a facade on database and ORM operations.

interface IFetchUsers {
   UserList GetAll();
   User GetById(int id);
}
interface ICalculateDebt {
   float GetDebt(int accountId);
}
interface IPersistOrder {
   void Save(Order order);
}

(forgive syntax errors, it's been a long time since I've done Java.)

These are injected via the constructor into your other classes and become trivial to mock, or even stub.

Then, for actual db code you just implement these interfaces. You can even put all implementations in a single class.

And that's it. No need to get fancy, but if you do want to get into fancier versions of this look into the repository design pattern (though I would argue that its not really necessary if using a good ORM).

George Mauer
  • 117,483
  • 131
  • 382
  • 612