Is mocking toString really possible in version 1.3?

1,486 views
Skip to first unread message

Jagger

unread,
Apr 18, 2008, 7:37:28 AM4/18/08
to mockito
Consider code below.

import org.mockito.Mockito;

public class ToStringDelegationTest {

private Object myObject;

/**
* @return the myObject
*/
public Object getMyObject() {
return myObject;
}

/**
* @param myObject the myObject to set
*/
public void setMyObject(Object myObject) {
this.myObject = myObject;
}

@Override
public String toString() {
return myObject.toString();
}

public static void main(String[] args) {
ToStringDelegationTest delegate = new
ToStringDelegationTest();
Object mockMyObject = Mockito.mock(Object.class);
delegate.setMyObject(mockMyObject);
System.out.println(delegate.toString());
Mockito.verify(mockMyObject).toString();
}
}

I want to check whether toString invocation is properly delegated.
It looks like the code is ok, but when run I got:

Mock for Object, hashCode: 31820984
Exception in thread "main"
org.mockito.exceptions.verification.WantedButNotInvoked:
Wanted but not invoked:
object.toString();
at
com.img.poligon.mockito.ToStringDelegationTest.main(ToStringDelegationTest.java:
33)

Moreover the toString() method is invoked for sure because
there is output from println.

So, my question is: Was it really added to version 1.3? :)

szczepiq

unread,
Apr 18, 2008, 9:02:34 AM4/18/08
to moc...@googlegroups.com
> So, my question is: Was it really added to version 1.3? :)

Kind of :)

I read the release notes and indeed the information is misleading. You
cannot verify toString() but you can stub it:

ToStringDelegationTest delegate = new ToStringDelegationTest();
Object mockMyObject = Mockito.mock(Object.class);

stub(mockMyObject.toString()).toReturn("foo");
delegate.setMyObject(mockMyObject);
assertEquals("foo", delegate.toString());

Verification of toString() is not possible because:

1. When I debug my IDE calls toString() on objects to print local
variables and their content, etc. After debugging, the verification of
toString() will most likely fail.
2. toString() is used for logging or during string concatenation.
Those invocations are usually irrelevant but they will change the
outcome of verification.

Cheers,
Szczepan Faber

Reply all
Reply to author
Forward
0 new messages