Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
     }
    }
like image 782
Artur Skrzydło Avatar asked Dec 05 '25 07:12

Artur Skrzydło


2 Answers

My best guess would be to make createService() method package private and create HelloMojoWrapperForTests that overrides it and always returns mock. But this seems like a huge workaround just for the sake of testing...

like image 124
Tomasz Bawor Avatar answered Dec 07 '25 20:12

Tomasz Bawor


Make createService() as protected and override this and return the mock in your test class while creating an anonymous class which extends HelloMojo. This way though your not testing the original class but a child of it but its pretty obvious that the child is just like the parent class except the overriden method which is intended.

public HelloMojoTest {    

     private HelloMojo helloMojo = new HelloMojo(){
   @Override
     protected SomeService createService() {
// return new or mocked or whatever instance you want
           return new SomeService();
     }
   }
 }
like image 37
Satish Avatar answered Dec 07 '25 19:12

Satish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!