samedi 9 janvier 2016

Writing testable code when new object is being constructed using Mockito only

So I am writing a class which I want to follow the best practices and be testable. I have a new object to be created inside it. So, I am following the factory pattern to achieve it.

public class apple{
private SeedFactory seedFactory; // factory object injected in class


public void myMethod(String property1, int property2, String depends){ // Method to be tested 
seedFactory = new SeedFactory(property1, property2); // Just to set the necessary parameter
SeedFactory result = seedFactory.getInstance(depends); // Factory pattern intact. Instance generation depends on only one parameter
}
}

Now, Before I actually create the new object, I have to make sure that I set two properties for the new instance to be generated, which are needed to be present irrespective of the type of instance generated by the factory. depends is the actual parameter which tells the factory what instance to return.

Now, as far as testability of this code is concerned, I can user PowerMockito to mock the factory object using whenNew but using PowerMockito is not a choice. I have to make it testable without it.

Also, I have tried to encapsulate the new call within a one line function and then use spy. But I want to avoid using spy, since it is not considered a good practice, in context of where this code is being used as a whole.

So my question is, Is there any way, without using PowerMockito, to re-write this class so that it can be unit tested properly?

If the instance to be generated needed only one parameter, then it would have been trivial. However, I don't want to pass more than one parameter to getInstance(). .

Aucun commentaire:

Enregistrer un commentaire