将值设置为模拟对象但获取 null

时间:2022-11-02
本文介绍了将值设置为模拟对象但获取 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实际 代码无关紧要,因为你在嘲笑它...而 Mockito 不知道 setNamegetName 之间存在关系.它不假定它应该将参数存储到 setName 并在调用 getName 时返回它......它 可以 这样做,但是据我所知,它没有.Mockito 提供的 mock 只允许您指定在其上调用方法时会发生什么,并检查以后调用了什么 .您可以模拟对 getName() 的调用,而不是调用 setName,并指定它应该返回的内容...

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:如何模拟 DriverManager.getConnection(...)? 下一条:Mockito ClassCastException - 无法投射模拟

相关文章

最新文章