
mockito - issue #472
Stubbing SuperClass Method Called From Overridden SubClass Method
What steps will reproduce the problem?
Create the following classes public class SuperClass{ private String name;
public boolean method(String name) { System.out.println("SuperClass Called"); if("INVALID".equals(name)) { return false;
} this.name = name; return true; } }
public class SubClass extends SuperClass{
private String subName;
public void method(String name) { boolean success = super.method(name); System.out.println("SubClass Called"); if(!success){ subName = name; } }
- Now using Mockito
public class TestMock{
private static final String DUMMY_STR = "DummyString";
@Before public void testMethod() {
SubClass sub = mock(SubClass.class,CALLS_REAL_METHODS);
doCallRealMethod().doReturn(false).when(sub).generate(DUMMY_STR);
sub.method(DUMMY_STR);
} }
What is the expected output? What do you see instead?
I expect only SubClass getting called and a console output "SubClass Called".
But what I see is even SuperClass gets called and prints console message.
What version of the product are you using? On what operating system? I see this in Mockito 1.9.5 On Windows XP/Eclipse
Please provide any additional information below. None
Comment #1
Posted on Feb 14, 2014 by Helpful BearCorrected a line:
doCallRealMethod().doReturn(false).when(sub).method(DUMMY_STR);
Comment #2
Posted on Feb 14, 2014 by Helpful BearCorrected Annotation: Replace @Before with @Test
Comment #3
Posted on Feb 24, 2014 by Happy PandaReturn types of methods in SubClass and SuperClass are different. Are you sure that there is no more changes?
Comment #4
Posted on Mar 4, 2014 by Happy Horse@alberskib is correct, the signature of method is different, so there is no overriding there, which means you have to stub both methods.
And anyway as you are using the answer that call real method, the bytecode still reference the method of the super class, there's is no polymorphism when the super
keyword is used.
Also I strongly advise you to avoid partial mocks, it can be a maintainance/evolutivity hell. You may want to refactor your design to use common behavioral patterns of the GoF, like the strategy pattern
I'm invalidating the issue, please raise a comment if you think it's really an issue.
Thanks for reporting though. Brice
Comment #5
Posted on Mar 5, 2014 by Helpful BearApologies for the delayed response. Signature of both the methods is same. It was a typo when I posted above example.
Status: Invalid
Labels:
Type-Defect
Priority-Medium