将值设置为模拟对象,但获取null [英] Set value to mocked object but get null

查看:96
本文介绍了将值设置为模拟对象,但获取null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类Foo要被嘲笑:

I have a simple class Foo to be mocked:

public class Foo {
   private String name;
   public Foo() {
   }
   public Foo(String name) {
     this.name = name;
   }

   public void setName(String name) {
     this.name = name;
   }
   public String getName() {
     return name;
   }
}

在单元测试代码中,我使用 Mockito 对其进行了模拟.

In my unit test code, I mock it by using Mockito.

Foo mockedFoo = Mockito.mock(Foo.class);
mockedFoo.setName("test");
// name is null
String name = mockedFoo.getName();

我在模拟对象中设置了name,但是当我调用getter获取名称时,它将返回 null .

I set name in mocked object, but when I call getter to get the name it returns null.

是Mockito特有的问题,还是被嘲笑的对象无法设置值的约定?这是为什么?嘲笑对象下面发生了什么?

Is it a Mockito specific issue or is it an convention that mocked object can't set value? Why is that? What is happening underneath with mocked object?

推荐答案

好吧-Foo actual 代码无关紧要,因为您在嘲笑它……而Mockito不知道setNamegetName之间应该有关系.它不假设它应该将参数存储到setName并在调用getName时返回它...它可以做到这一点,但是据我所知意识到的. Mockito提供的模拟仅允许您指定调用方法时发生的情况,并检查稍后调用了什么 .除了调用setName之外,您还可以模拟对getName()的调用并指定应返回的内容...

Well yes - the actual code of Foo doesn't matter, because you're mocking it... and Mockito doesn't know there's meant to be a relationship between setName and getName. It doesn't assume that it should store the argument to setName and return it when getName is called... it could do that, but it doesn't as far as I'm aware. The mock provided by Mockito just allows you to specify what happens when methods are called on it, and check what was called later on. Instead of calling setName, you could mock a call to getName() and specify what it should return...

...或者您可以直接使用Foo而不是模拟它.别认为您不必在测试中嘲笑一切.当您使用实型类时,只需模拟(或伪造)尴尬的内容即可,例如因为它使用文件系统或网络.

... or you could just use Foo directly instead of mocking it. Don't think you have to mock everything in your tests. Just mock (or fake) things that are awkward when you're using the real class, e.g. because it uses the file system or network.

这篇关于将值设置为模拟对象,但获取null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆