Java 如何使用 Mockito 在模拟对象上设置属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19920271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:23:33  来源:igfitidea点击:

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

javajunitmockito

提问by ankit

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?

当我尝试打印此属性时,我得到null. 如何设置此属性?

采纳答案by Makoto

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

回答by Dzung BUI

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

Mock 对象不是您存储数据的地方,而是让您在调用其方法时教授行为。

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

试试这个: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

回答by 8bitjunkie

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

恐怕你在滥用你的 mock SlingHttpRequest

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

Mockito 要求您在测试场景中使用它们之前连接模拟的属性,即:

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

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

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

您不能setAttribute(final Attribute a)像这样在测试期间调用该方法:

slingHttpRequest.setAttribute(someObject);

slingHttpRequest.setAttribute(someObject);

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

如果你这样做,当测试运行时,getAttribute()将返回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.

顺便说一句,如果您正在单元测试的代码将以这种方式在您的模拟上调用 setter,请不要使用模拟。使用存根