Is it possible to mock service which is created in class under test?

Artur Skrzydło :

I would like to be able to mock SomeService, however, because it's a maven plugin, I'm out of control how this class is created. I need to create SomeService manually, because I can't use it in constructor or in other place. In a test I can mock SomeService - but it will be replace by new instance created in execute() method. Is it possible to mock this service in other way than using PowerMockito ??

@Mojo(name = "hellomojo")
    public class HelloMojo extends AbstractMojo {    

     private SomeService service;    

     @Override
     public void execute() throws MojoExecutionException {     
        service = createService();
     }

     private SomeService createService() {
           return new SomeService(parameter);
     }
    }
Artur Skrzydło :

My final solution to this problem is following. First of all I've extracted service creation to separate class like :

public class ServiceProvider {

    public SomeService createService() {
        return new SomeService();
    }
}

Then, in my HelloMojo I've created two constructors, where default one uses constructor which set SomeService. Finally my HelloMojo class looks like :

    @Mojo(name = "hellomojo")
    public class HelloMojo extends AbstractMojo {    

     private SomeService service;  

    public HelloMojo(){
       this(new SomeService())      
    }   

    public HelloMojo(SomeService someService){
       this.service=someService;
    }   

     @Override
     public void execute() throws MojoExecutionException {     
        service.doSomething
     }             
    }

So, I've just did some dependency injection

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=103298&siteId=1