Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a property on a mocked object using Mockito?

Tags:

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?

like image 721
ankit Avatar asked Nov 12 '13 03:11

ankit


People also ask

How do you set a value to a mocked object?

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");

How do you initialize a mocked object?

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.

What is the syntax of mocking an object using Mockito?

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.

How can specify the mock behavior of an object in Java?

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.


2 Answers

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); 
like image 52
Makoto Avatar answered Oct 11 '22 23:10

Makoto


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.

like image 43
8bitjunkie Avatar answered Oct 12 '22 00:10

8bitjunkie