Set value to mocked object but get null

By default mockito has no behavior, on any methods in the mocked object.

You should do something like this:

Foo mockedFoo = Mockito.mock(Foo.class);
when(mockedFoo.getName()).thenReturn("someName");
String name = mockedFoo.getName();

edit: as mentioned by Jon Skeet, you should not need to mock things that can just be tested in a normal fashion.


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.