Reputation: 5127
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?
Upvotes: 27
Views: 54943
Reputation: 1474
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")
Upvotes: 0
Reputation: 13245
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.
Upvotes: 3
Reputation: 188
Mock object is not where you store data, it's for you to teach the behavior when its methods are invoked.
Upvotes: 0
Reputation: 106390
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);
Upvotes: 41