I have been pushing myself to learn more and more Unit Testing techniques as of late and ran into something I just can’t figure out- namely, how to even get started. I am trying to unit test a factory with a very, very simple single method. I have simplified it using example names for you helpful folks.
public class HandlerFactory extends SecondHandlerFactory
{
//To hold singleton of this class.
private static SecondHandler factoryInstance = null;
private HandlerFactory() throws HandlerCreationException
{
super();
}
protected InterfaceExample createSomethingByThisKey(String key) throws HandlerCreationException
{
InterfaceExample myNewHandler = null;
if (StringFunctions.isEqualIgnoreCase(key, "Phone"))
{
myNewHandler = new PhoneHandler();
}
}
}
I’m having major trouble figuring out to set up this test to even fall into the createSomethingByKey(). Even then, I can’t even figure out how I would do my assertEquals() method correctly.
Right now, I have stuff set up to to do a createInstance(); but nothing seems to make any sense to me in how to fall into this. The added variable and interfaces are making me hella confused here. It seems simple to test and is a very, very short class- but not being exposed to this (Java isn’t even my first language) is kind of a hard wall for me to get over).
Any help on how to set up either a standard JUnit or Mockito (doesn’t matter really) on how to set all this up? Also the fact that’s protected is making me even more clueless since proper standard is to have Unit Tests in another package.
Honestly I am not sure what’s your difficulties. I can only guess 2:
For 1, it is in fact not that difficult, just assume the method you are testing is public:
The logic in this method is simply creating a handler instance base on the key. So your test should aim to see if correct type of handler is created according to your key. Therefore the tests should be something like:
For problem 2 (restricted access to protected method), you usually have 2 choices:
We normally have test sits in same package as the system under test (SUT), so you should be able to invoke the protected method.
You may also choose to create a Test-Specific Subclass (TSS) which expose a method which directly delegate to the protected method in SUT (or override to loosen the visibility of the method), and have your test performed against the TSS. Of course, you should make sure that your SUT can be extended. It may looks something like this
Create a TSS like this:
Then you can freely test on that protected method (it is seldomly used in Java I believe, coz we can always invoke protected method by putting test under same package as SUT)