Mocking a public field

10,760 views
Skip to first unread message

Logdog82

unread,
May 12, 2011, 10:15:39 AM5/12/11
to moc...@googlegroups.com
Hi @ll,

how can I mock public fields? Example:

when(mockFoo.myField).thenReturn("bar");

Mockito gave me an Exception with the message "when() requires an argument which has to be 'a method call on a mock'". The problem is that I have no acess to the mocked interface (so I could change the field to a get method) because it's in a external library.

Thanks.

Brice Dutheil

unread,
May 12, 2011, 12:49:40 PM5/12/11
to moc...@googlegroups.com
Hi,

Hmm I'm not sure what you really trying to do. But you cannot mock fields.

If it's *legacy* code, I would create a package protected method in your code that read the interface field. And in your test code, stub that method.

Something like:


ProductionCode implements ThirdPartyInterface {
// ...

  public void theMethodThatDosBusinessStuff() {
    // ...
    String thing = readThirdPartyInterfaceField();
  }

  String readThirdPartyInterfaceField() {
    return ThirdPartyInterface.theThing;
  }
}


ProductionCodeTest {
  public void my_code_should_do_the_following() {
    // given
    ProductionCode pcMock = mock(ProductionCode.class);
    given(pcMock.readThirdPartyInterfaceField()).willReturn("something else");

    // when

    // then

  }
}


Hope that helps,


-- 
Bryce


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

Logdog82

unread,
May 13, 2011, 9:36:47 AM5/13/11
to moc...@googlegroups.com
Hi,
thanks for your post. I will try it.

Brice Dutheil

unread,
May 13, 2011, 10:04:53 AM5/13/11
to moc...@googlegroups.com
Hi,

You're welcome.
As a reminder, you should only mock, types that you own, not type in third party library.



-- 
Bryce


On Fri, May 13, 2011 at 15:36, Logdog82 <logd...@gmail.com> wrote:
Hi,
thanks for your post. I will try it.

--

David W

unread,
May 15, 2011, 4:59:46 AM5/15/11
to mockito
Why can't you just write
mockFoo.myField = "bar";

After all, a mocked object is still a member of the original class, so
it has the same public fields. It's only the methods that get
overridden.

Cheers,
David.
Reply all
Reply to author
Forward
0 new messages