kokalsuhas / mockito

Automatically exported from code.google.com/p/mockito
0 stars 0 forks source link

Mockito spy fail to handle abstraction correctly #506

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
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

GoogleCodeExporter commented 8 years ago
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