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
Joined: Sep 24, 2006
Posts: 4
posted
0
Oops I mean public/protected not private!!
Lasse Koskela
author
Sheriff
Joined: Jan 23, 2002
Posts: 11962
5
posted
0
I often go for overriding the troublesome method in an anonymous subclass as follows:
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.
SCJP 1.4, SCWCD 1.3, SCBCD 1.3
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
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.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Stephen Masters
Greenhorn
Joined: Oct 09, 2003
Posts: 6
posted
0
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.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.