25

I have a scenario where I have to set a property of a mocked object as follows:

SlingHttpRequest slingHttpRequest= mock(SlingHttpRequest);
slingHttpRequest.setAttribute("search", someObject);

When I try to print this attribute I get null. How do I set this property?

Makoto
  • 104,088
  • 27
  • 192
  • 230
ankit
  • 4,919
  • 7
  • 38
  • 63

4 Answers4

39

You don't normally set properties on your mocked objects; instead, you do some specific thing when it's invoked.

when(slingHttpRequest.getAttribute("search")).thenReturn(someObject);
Makoto
  • 104,088
  • 27
  • 192
  • 230
3

I'm afraid you're misusing your mock SlingHttpRequest.

Mockito requires you to wire up your mock's properties before you use them in your test scenarios, i.e.:

Mockito.when(slingHttpRequest.getAttribute("search")).thenReturn(new Attribute());

You cannot call the setAttribute(final Attribute a) method during the test like so:

slingHttpRequest.setAttribute(someObject);

If you do this, when the test runs, getAttribute() will return null.

Incidently, if the code you are unit testing is going to call a setter on your mock in this way, do not use a mock. Use a stub.

8bitjunkie
  • 12,793
  • 9
  • 57
  • 70
0

Mock object is not where you store data, it's for you to teach the behavior when its methods are invoked.

try this: https://www.google.com/search?q=mockito+example&oq=mockito+example&aqs=chrome..69i57j0l5.6790j0j7&sourceid=chrome&espv=210&es_sm=93&ie=UTF-8

Dzung BUI
  • 188
  • 2
  • 9
  • You do answer the question, but the link doesn't add much more than what could be found in a Google search. Consider editing it or adding examples. – Makoto Nov 12 '13 at 03:40
  • What I meant was that the examples for this topic can be found easily by a simple key word – Dzung BUI Nov 12 '13 at 03:56
  • 2
    Then it's honestly more of a comment than an answer, to be frank. – Makoto Nov 12 '13 at 03:58
  • @Makoto I disagree. OP is mocking a class that maybe shouldn't be mocked. It's not clear to me whether `SlingHttpRequest` is a class or an interface - I can't find it in the sling docs. But if it's a class, then it seems to be about storing data, not executing functionality; and that implies that there is nothing to be gained by mocking it. So the first sentence of this post is the correct answer - it's just somewhat let down by the google link, but still worth a +1. – Dawood ibn Kareem Nov 13 '13 at 05:24
-1

I'm probable 7 years late for the party, but I still would like to contribute.

You CAN set class property using the Whitebox from powermock:

Whitebox.setInternalState(mockedClass, "internalField", "Value to be returned")
Rodrigo Borba
  • 1,334
  • 1
  • 14
  • 21