• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Testing private DAO method

 
Kevin N Shah
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm wondering how a DAO class with following private method can be refactored in a best way so that it can be testable-

private Connection getConnection(){....}

I think it can be done in couple of ways. Not sure which is more appropriate!
1. Make it public/private and override in a subclass
2. Override using a anonymous class in test class rather than using subclass.
3. ??

Any suggestion or comments?

Thanks.
Kevin
 
Kevin N Shah
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops I mean public/protected not private!!
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I often go for overriding the troublesome method in an anonymous subclass as follows:

 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a method should be private, then keep it private. But you won't be able to override it because it is implicitly final. The solution is to use Reflection. I like to use PrivilegedAccessor as it makes life a bit easier.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Besides the point that I think a private method that needs testing is a code smell, I did understand Kevin to say that he actually wants to use some kind of test double for the connection. For that I like Lasse's approach.
 
Stephen Masters
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Depending on how you're getting your connection, you could try what I do. For my DAOs I tend to be getting a data source on an application server. Therefore in my getConnection() methods, if the datasource is null, I'm calling the initialiseDataSource method below:

In the root of my test tree I have the following class:

TestConstants is just an interface with some public static constants to define where to look. With those in place, all I need to do is initialise my test context at the start of each TestCase that makes use of it;

The advantage of this is that all you need to do is change a constant in your test source to point at a different appserver/database by enforcing an InitialContext on a development server.

Assuming that you are able to do this, to me it seems preferable to setting test properties in your main source code. But remember that this is more an integration test than a unit test, so it will only work when your appserver is running.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic