tags:

views:

138

answers:

2

Hi, actually im doing some tests with Mockito. I have the following class:

class BaseService{

public void save(){...}

}

public Childservice extends BaseService{
public void save(){
//some codes
super.save()

}

}
I want to mock only the second call (super.save) of the ChildService & do nothing so the test is successfull.The first call must call the real method. Is there a way to do that ?

+1  A: 

No, Mockito does not support this.

This might not be the answer you're looking for, but what you're seeing is a symptom of not applying the design principle:

Favor composition over inheritance

and what you're trying to do is a straight violation of Liskov (yes I mean you cannot do that in tests either).

If you extract a strategy instead of extending a super class the problem is gone.

If however you are not allowed to change the code, but you must test it anyway, and in this awkward way, there is still hope. With some AOP tools (for example AspectJ) you can weave code into the super class method and avoid it's execution entirely (yuck). This doesn't work if you're using proxies, you have to use bytecode modification (either load time weaving or compile time weaving). There might be mocking frameworks that support this type of trick as well.

I suggest you go for the refactoring, but if that is not an option you're in for some serious hacking fun.

iwein
A: 

If you really don't have a choice for refactoring you can mock/stub everything in the super method call e.g.

class BaseService{
    public void save(){
        validate();
    }
}

public ChildService extends BaseService{
    public void save(){
        super.save()
        load();
    }
}

@Test
public void testSave() {
    ClildService spy = Mockito.spy(new ChildService());

    // Prevent/stub logic in super.save()
    Mockito.doNothing().when((BaseService)spy).validate();

    // When
    spy.save();

    // Then
    verify(spy).load();
}
jgonian