how to stub inherited parent methods?

10,238 views
Skip to first unread message

romanosipov

unread,
Nov 25, 2010, 7:06:37 AM11/25/10
to mockito
does anybody knows how to stub inherited parent method? For example,
there are to classes:

class A {
void methodA() {
// do something
}
}

class B extends A {
void methodA() {
if (some condition) {
super.methodA();
} else {
// do something yet
}
}
}

suppose, there is a good test case for the class A and methodA was
tested, in test case for classB it would be good to test only the fact
of methodA call in super class, because methodA itself is good tested,
how can i do this? this is an exmaple of what i want to do^

public class BTestCase {
/** Testing class. */
private B b;

@Before public void setUp() {
this.b = new B();
this.b = spy(this.b);
}

@Test public void methodA() throws Exception {
// some condition is true
doNothing().when(this.b).super.methodA(); // how to realize
this construction?
}
}

Felix Leipold

unread,
Nov 25, 2010, 8:07:08 AM11/25/10
to moc...@googlegroups.com
This is a tricky case. I think trying to push for support of this idiom in mockito will not be successful.

I would argue that you rather want to do a replace-inheritance-with-delegation-refactoring. Does B really need to extend A? If this is really the case why do you want to test B in isolation?

Cheers,
Felix 


--
You received this message because you are subscribed to the Google Groups "mockito" group.
To post to this group, send email to moc...@googlegroups.com.
To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mockito?hl=en.


Brice Dutheil

unread,
Nov 25, 2010, 8:37:11 AM11/25/10
to moc...@googlegroups.com
Hi,

That's why inheritance can be dangerous in object oriented programming, you really should choose composition over inheritance.
Inheritance can break encapsulation.

In this particular case I would agree with Felix. You might want to create an or several interfaces, then compose your object B with A or others.

Another solution, which is in my humble opinion a very probable code/design smell, is to extract your super.methodA() in a package protected method so you can stubIt.

eg:
class A {
   void methodA() { }

}

class B extends A {
   void methodA() {
       if (some condition) { callSuperMethodA(); }
       else { /* do something yet */ }
   }

   void callSuperMethodA() { super.methodA(); }
}

@RunWith(MockitoJUnitRunner.class)
public class BTestCase {
  @Spy private B b;


  @Test public void methodA() throws Exception {
    doNothing().when(b.callSuperMethodA());
   
    b.methodA();
    // don't fail
  }
}


Again I really would go for composition and delegating, that's more object oriented.


Hope that helps :)

-- 
Bryce
Reply all
Reply to author
Forward
0 new messages