javamockito

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?


Solution

  • 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);