Ken Y-N
Ken Y-N

Reputation: 15008

Mocking a method in an element of a list

I have this code in my Subject Under Test:

public class Widget {
    private Set<Thing> things;
    public Set<Thing> getThings() { return things; }
    public void setThings(Set<Thing> things) { this.things = things; }

    public void performAction(PerformingVisitor performer) {
        for (Thing thing: getThings())
        {
            thing.perform(performer);
        }
    }
}

My JUnit/Mockito test looks like:

@RunWith(MockitoJUnitRunner.class)
public class WidgetTest {
    @Mock private PerformingVisitor performer;
    @Mock private Thing thing;
    @InjectMocks private Widget widget;

    @Before
    public void setUp() throws Exception {
        Set<Thing> things = new HashSet<Thing>();
        things.add(thing);
        widget.setThings(things);

        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void shouldPerformThing() {
        Mockito.when(thing.perform(Mockito.any(PerformingVisitor.class))).thenReturn(true);

        widget.performAction(performer);

        Mockito.verify(thing).perform(Mockito.any(PerformingVisitor.class));
    }
}

However, this gives me the error:

Wanted but not invoked:
thing.perform(<any>);
    -> at com.myclass.ThingTest.shouldPerformThing(WidgetTest.java:132)

I've verified that the code enters the for loop and should be calling the actual thing.perform(performer); line, but my mock does not seem to be recording a call.

Upvotes: 1

Views: 72

Answers (2)

gontard
gontard

Reputation: 29520

From the MockitoJUnitRunner javadoc:

Initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.initMocks(Object) is not necessary.

So, if you remove

 MockitoAnnotations.initMocks(this)

from your setUp method, the test pass.

Upvotes: 1

troig
troig

Reputation: 7212

I think you need initMocks before the mock injection.

Could you try to change your setUp method for this:

   @Before
   public void setUp() throws Exception {
      MockitoAnnotations.initMocks(this);
      Set<Thing> things = new HashSet<Thing>();
      things.add(thing);
      widget.setThings(things); 
   }

Hope it works

Upvotes: 1

Related Questions