An example of scenario I'm trying to unit test somehow:
A method gets three parameters: Company name, Plane Number 1, Plane Number 2
public Double getDistanceBetweenPlanes(Sting company, String plane1, String plane2)
{
-Apply some validation logic to see that plane numbers and company realy exists
-Use complex geLocation and setelate data to get plane location
return plane1.geoLocation() - plane2.geoLocation() ;
}
Now, I want to unit test this.
I do not have real plane numbers, I do not have live connection to the satellite.
Still I would like to be able to mock the whole thing somehow so that I can test this API. Any suggestion on how to refactor it? Any new public method to be created just for testing?
Usually when refactoring non-tested code, I'm referring to what I would do when practicing TDD and BDD.
So first I would write a simple contract, one line = one requirement (of the existing code). Then while coding the test, I would probably notice things I don't want to test. In this case, DI will help you remove the code that has different responsibility to another class. When working in a object design it is important to focus on behavior and interaction between objects with different concerns. Mockito, with is alias class BDDMockito, can help you favor this approach.
In your case, here's an example of what you can do.
A simple JUnit test might look like (using features from mockito 1.9.0) :
And you will have the following dependencies injected, each having his own unit test describing how the class behaves, considering the input and the collaborators :
Using this way you can refactor your code with a much lower coupling. The better separation of concerns will allow a better understanding of the code base, a better maintainability, and easier evolution.
I also would like to redirect you to further reading on this blog post The Transformation Priority Premise in TDD from the famous Uncle Bob Martin http://cleancoder.posterous.com/the-transformation-priority-premise