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; } }
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();
I set name
in mocked object, but when I call getter to get the name it returns null.
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?
Advertisement
Answer
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…
… 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.