Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify if inherited super class method was called from method being tested or not

Ok so I'm stuck with Mockito again. Here's the situation:

I've a super class, and a subclass:

class Parent {
    protected void insertData() { 
        // Here is some database related stuff
        someObject.storeData();
    }
}


class Child extends Parent {

    private String name;

    public void printHierarchy(int x) {
        if (x > 1) {
            insertData()
        } else {
            System.out.println("Child");
        }

    }
}

And in my unit test class, I'm testing Child class printHierarchy() method:

@RunWith(SpringJUnit4ClassRunner.class)
public class ChildTest {

    @InjectMocks  // To inject mock objects
    private Child child = new Child();    

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        // This is where the issue is
        doNothing().when(child).insertData();
    }

    @Test
    public void testPrintHierarchy() {
        child.printHierarchy(5);
        // Here also
        verify(child, times(1)).insertData();
    }
}

So the issue is, how do I verify if insertData() method was called from Child#printHierachy()?

When I try the above code, I get the error as:

Argument passed to when() is not a mock!

Of course, child is not a mock. I'm testing that class. But how do I resolve this issue?

No I haven't found any duplicate of this. One question was pretty similar though, but it didn't help me.

like image 208
Rohit Jain Avatar asked Feb 03 '26 18:02

Rohit Jain


2 Answers

You need to use spy() for that. The following code works:

public final class Bin
{
    @Test
    public void spyMe()
    {
        final Child c = spy(new Child());
        doNothing().when(c).printParent();
        c.printHierarchy(1);
        verify(c).printParent();
    }
}

class Parent {
    protected void printParent() { System.exit(0);}
}

class Child extends Parent {

    private String name;

    public void printHierarchy(int i) {
        if (i > 0)
            printParent();
    }
}
like image 160
fge Avatar answered Feb 05 '26 07:02

fge


I think you need to use a spy for Child instead of a mock.

like image 39
geoand Avatar answered Feb 05 '26 08:02

geoand



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!