rickygrimes
rickygrimes

Reputation: 2716

How do I use setters on mocked object?

Can a setter be used on a mocked object? I have a regular class that I have mocked, and I need to set some values for the mocked object.

Can I use setters on the mock object?

Upvotes: 1

Views: 1836

Answers (2)

Pranay Kumar
Pranay Kumar

Reputation: 1

You can use a setter on a mocked object which does not raise any error, but while calling any getter, you will get null unless you configured a way for getter, because getter is also like any other method.
Do like:

when(mockObject).getName().thenReturn("someName");

That would work.

Upvotes: 0

durron597
durron597

Reputation: 32323

Don't mock data structures (like List and Map), and don't mock POJOs. Just use the real object. The idea behind mocking is to remove behavior from the equation, not data storage.

If the class is not a POJO, then you don't actually have to use a setter, you can just use when functionality for the getter, e.g.

when(mock.getSomeValue()).thenReturn(aRealValue);

Upvotes: 3

Related Questions