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?
To solve your problem of knowing whether the setName() method was called in your code with the specified value use the Mockito verify method. For example: verify(mockedFoo, times(1)). setName("test");
For the mocks initialization, using the runner or the MockitoAnnotations. initMocks are strictly equivalent solutions. From the javadoc of the MockitoJUnitRunner : JUnit 4.5 runner initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.
Mock will be created by Mockito. Here we've added two mock method calls, add() and subtract(), to the mock object via when(). However during testing, we've called subtract() before calling add(). When we create a mock object using create(), the order of execution of the method does not matter.
We can mock an object using @Mock annotation too. It's useful when we want to use the mocked object at multiple places because we avoid calling mock() method multiple times. The code becomes more readable and we can specify mock object name that will be useful in case of errors.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With