Mocking private methods while testing

Having been working with mocking frameworks for quite sometime, mostly easymock, I always wondered some way of mocking the private methods and then testing them in isolation as I would do for any non-private methods. There has been no direct support for doing this in any of the popular mocking frameworks till now. So I was left with very few options

  • Make them protected ( a hack as this is going to break my design and encapsulation), thus making it available to test in isolation. Also now I can override that method with an empty implementation while testing other public/protected methods which makes a call to this method, thus in a way trying to stub it.
  • Leave them as private and have them tested as part of another method test so that it is covered as part of code coverage tool, but still has no way of testing it in isolation and also at the same time it might get executed multiple times if it is invoked from multiple methods

But recently I came across another mocking framework powermock which is sort of extension on top of easymock to allow mocking of not all private methods but also of static methods, constructors, final methods etc. It uses bytecode instrumentation and a custom classloader to do this which is OK but a little more intrusive then what I would have liked.

There is good enough documentation to depict how to mock private methods here . Also it provides some useful reflection utilities which can be used in unit testing private methods, some examples of which can be found here

Non-indexed foreign keys

Let me start my first accepting a misconception which I had till very recently. I sort of always assumed that foreign keys are always indexed. A little more digging revealed that Oracle, DB2 and even SQL server does not create an index for a foreign key automatically. So it has to be explicitly done.
We all know indexes has cost associated to it. Apart from using the storage space, it has to be maintained by the database on inserts and updates but still it is very good idea to create an index for a foreign key and especially when

  • We have a use case where deletion of the parent row cascades into deletion on the child table. Otherwise it will lead to a full table scan of the child table for each parent row deletion.
  • We frequently join parent and child tables. Otherwise it will have a performance impact.

So basically a little bit of a trade off as what we really want to do but in general it is always a good idea to have an index on a foreign key.

But does all this have any impact on how we do our Hibernate mappings, yes for sure. So for example if we decide to not index a foreign key, then

  • Be careful while using : on-delete=”cascade” even though the database has a support for it
  • Always specify lazy=”true” to prevent a join and eager fetch of the child rows.