projoy/mockito

Mockito spy fail to handle abstraction correctly

GoogleCodeExporter opened this issue · 1 comments

Hello,

To reproduce it :

We have abstract class containing 2 public methods implemented and one pure 
virtual method
ex :

public abstract class AbstractClass {
  public abstract int getValue();

   public void first_method() {
     if (getValue() == 0) {
        second_method(new String("Val"));
     }
   }

   // Method must be never called in the test method
   public void second_method(String val) {
     if (getValue() == 0) {
        val.toString(); // Null Pointer exception here
     }
   }

}

1) Create an extended class from the abstract that implement the virtual method

public class ConcreteClass extends AbstractClass {

  private int value;

  public ConcreteClass() {
    this.value = 0;
  } 

  private void setValue(int val) {
     this.value = val;
  }

}

2) Create a test that:

@Test
public void test_Spy() {
  ConcreteClass target = spy(new ConcreteClass());
  target.setValue(1);
  target.first_method();
  verify(target, never()).second_method(anyString()); // Exception catched here
}


Original issue reported on code.google.com by tabouf...@gmail.com on 25 Feb 2015 at 5:40

Hi,

Spy cannot work around such design, internal calls are not intercepted in the 
current implementation, only external interactions. And that would be probably 
be  a design issue. The code design should favor composition. In this snippet 
if the second method is in a Collaborator with related responsibilities then 
the code won't need Spies and the would just be ensuring invocations are made 
to this mocked collaborator.

Generally speaking spies should be avoided in such cases to favor composition.

Original comment by brice.du...@gmail.com on 25 Feb 2015 at 5:58

  • Changed state: WontFix