Akshay Arora
Akshay Arora

Reputation: 1945

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 {
    // factory object injected in class
    private SeedFactory seedFactory; 

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

EDIT: Adding code for factory as well.

public class SeedFactory{
String property1;
int property2;

SeedFactory(property1,property2){
this.property1 = property1;
this.property2 = property2;
}
SeedFactory getInstance(int depends){
if(depends == 1)
{ // do stuff }
else{ // do stuff and return instance }

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().

Upvotes: 0

Views: 234

Answers (2)

Duong Nguyen
Duong Nguyen

Reputation: 850

I think you're doing something wrong.

If SeedFactory isn't an Apple's dependency but an internal concern, hence you don't need to mock a SeedFactory to test Apple. You should test the public API provided by Apple only.

If SeedFactory is an Apple's dependency, so it definitely should be injected.

Upvotes: 0

SMA
SMA

Reputation: 37023

SeedFactory is not Apple's dependancy but your method depends on SeedFactory which has "uses" relationship. So to define proper relation i would suggest you use "USES" relation as below:

public void myMethod(SeedFactory seedFactory, String depends){ // Method to be tested 

Now you could mock SeedFactory and can unit test it appropriately.

Upvotes: 2

Related Questions