can't get when().thenReturn() to work as expected

3,859 views
Skip to first unread message

Matt

unread,
Jan 20, 2012, 8:38:46 PM1/20/12
to mockito
hey everyone,

New to Mockito (as in 2 days maybe) - using mockito-all-1.9.0 with
powermock-mockito-1.4.11-full...

I have the following classes and corresponding test:

public class MyClass {
public boolean getBol() {
return false;
}
}

public class Run {
public String run() {
MyClass clazz = new MyClass();
if(!clazz.getBol()){
return "false";
}
return "true"
}
}

public class TestMyClass {
@Test
public void testMyClass() {
MyClass mock = mock(MyClass.class);
when(mock.getBol()).thenReturn(true); //I've tried
variations of this like doReturn() and doAnswer() but same result

Run run = new Run();
assertTrue(run.run().equals("true");
}

}

My test keeps failing telling me that the actual instance of getBol is
being called, not the mock. I'm sure it's something very simple I'm
overlooking.

All help is greatly appreciated.

Thanks,

Matt

Krisztian Milesz

unread,
Feb 7, 2012, 3:37:17 AM2/7/12
to moc...@googlegroups.com
In your Run class you use a new instance of MyClass not your mock.You
could modify Run and inject an instance of MyClass, then you'll be
able to pass in your mock.

Regards,
Krisztian

> --
> 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.
>

Reply all
Reply to author
Forward
0 new messages