Stubbing instanceOf

4,998 views
Skip to first unread message

Patricio Arvizu

unread,
Jun 12, 2009, 6:30:53 PM6/12/09
to mockito
Hi,

Is there a way to stub interactions with the instanceof operator in
Java?

I have something like:

public class SystemUnderTestTest
{
public void test()
{
MyClass mockMyClass = mock(MyClass.class);
SystemUnderTest sut = new SystemUnderTest();
sut.foo(mockMyClass);
}
}

public class SystemUnderTest
{
public void foo(IMyClass myClass)
{
if (myClass instanceof MyClass)
{
//Do something
}
else
{
//Throw exception
}
}
}

Thanks!

szczepiq

unread,
Jun 13, 2009, 2:32:27 AM6/13/09
to moc...@googlegroups.com
Hi,

>Is there a way to stub interactions with the instanceof operator in
>Java?

Sure. Create an object or a mock of X type and the instanceof will
pass. Create an object or a mock of Y type and the instanceof will
fail. That's all you need really to be able to describe the behavior
of your class in the test.

Cheers,
Szczepan Faber

Patricio Arvizu

unread,
Jun 13, 2009, 4:45:57 PM6/13/09
to mockito
I don't have access to my source code right now but I'm pretty sure I
tried and it was not as simple as that.

When I created a mock of MyClass, calls to instanceof MyClass would
return false, since the mock's type was something like "MyClass
$EnhancedByMockito219781723" or at least that's what the Eclipse
debugger showed.

Is there a way to get around this? How does instanceof work
internally? Does it call getClass()? Would it be a good idea to stub
this method?

Thanks!
-Patricio

szczepiq

unread,
Jun 13, 2009, 5:21:31 PM6/13/09
to moc...@googlegroups.com
Hi,

Have a look at javadoc on instanceof:
http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isInstance(java.lang.Object)

Then you might try this in your code:

List mock = mock(List.class);
assertTrue(mock instanceof List);

Hope this helps,
Cheers,
Szczepan Faber

Patricio Arvizu

unread,
Jun 18, 2009, 11:47:11 AM6/18/09
to mockito
I was mocking the wrong interface... duh.

Thanks for your answers anyway.

On 13 jun, 16:21, szczepiq <szcze...@gmail.com> wrote:
> Hi,
>
> Have a look at javadoc on instanceof:http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isInstance...)
>
> Then you might try this in your code:
>
> List mock = mock(List.class);
> assertTrue(mock instanceof List);
>
> Hope this helps,
> Cheers,
> Szczepan Faber
>
Reply all
Reply to author
Forward
0 new messages