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

三世轮回 提交于 2019-12-29 07:38:30

问题


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?


回答1:


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



回答2:


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




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



来源:https://stackoverflow.com/questions/19920271/how-do-i-set-a-property-on-a-mocked-object-using-mockito

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!