lundi 29 juillet 2019

How to unit test new object creation in interface default method?

There is a default method in the interface that creates new object and uses its functions. So I need to mock it. But I can't figure it out without making another default method which returns new instance. I used to make factories so far that handles object creation and than mock the factory method. But can't do it in interfaces since interfaces can't have instance variables which is factories in this scenario. Any other ideas? I want to be consistent in the project but now I have 2 different approach to avoid object creations in methods. Here is an example:

public interface ISomeInterface
{
    default Object callMe( )
    {
        Object someObject = new Object( ); // need to mock this
        Integer result = someObject.finish();
        result = result + 1;

        return result;
    }
}

I used to refactor the code with factories when I don't use interface like this;

default Object callMeNotInterfaceClass( )
{
    Object someObject = new Object( );
    Integer result = instanceFactory.create().finish(); // I can mock create() method 
    result = result + 1;

    return result;
}

Only solution I implemented so for wrapper method:

public Object callMe( )
{
    Object someObject = new Object( );
    Integer result = wrapperMethodCall.finish(); // only solution so far. But now I have 2 different approaches in the project to avoid object creation.
    result = result + 1;

    return result;
}

default Object wrapperMethodCall() {
    return someObject.someMethodsToBeMocked();
}

Aucun commentaire:

Enregistrer un commentaire