Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock super reference (on super class)?

Sometimes when I write unit tests I should to mock reference to superclass.

I have read this question: question

This answer answer with DI advice to refactor code. But I cannot it

this answer another answer is not suitable if superclass method is enough big. In my case I have very big code. Yes I know that it is brokes SOLID OOD principes but I just should to write test. I have not enough time for refactor.

said question was asked 4 years ago!

Does currently Mockito or Powermock can resolve this issue ?

update

code example:

class BaseService {  
    public void save() {
      // a lot of code here! I cannot change this code.
    }  
}

public Childservice extends BaseService {  
    public void save(){  
        //logic for testing
        super.save();
       //logic for testing
    }  
} 

update 2

public class Parent {
    public int save() {
         return 99;
    }   
}

public class Child extends Parent {
    public int save() {
        int i = super.save();
        return i*2;
    }
}

and test:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Parent.class)
public class ParentTest {
    @Test
    public void testSave() {       
        PowerMockito.suppress(PowerMockito.methodsDeclaredIn(Parent.class));        
        System.out.println(new Child().save());
    }
}

output: 198

like image 204
gstackoverflow Avatar asked May 26 '14 08:05

gstackoverflow


People also ask

How do you call the super class method in subclass?

Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.

Can we mock constructor using Mockito?

Starting with Mockito version 3.5. 0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes.

How do I use Mockito doNothing?

Mockito 's doNothing() is used when you want to test void methods because void methods do not return anything so there is no way you can verify using assert. These void methods may be anywhere, for example, in service class, in dao class, etc.


1 Answers

With Powermock you can replace or suppress methods, so it is possible to change the action done by BaseService.save(). You can also make methods to do nothing with suppressing. You can even suppress static initializer blocks.

Please read this blog entry of the Powermock authors. See chapter "Replacing".

UPDATE:

Suppress seems to work for me, but replace not. See the picture below: enter image description here

like image 174
Gábor Lipták Avatar answered Sep 23 '22 23:09

Gábor Lipták