How to mock a setter of a model

When you are building a unit test you may need to assert the value given to a setter. By default all the setters of a mock object (with Mockito) do nothing.

Required Steps

  1. Define your mock model as a field of your test class
  2. Define a field in your test class to hold the value that you want to assert
  3. Mock the setter to save the parameter in your field.
  4. Assert the value

Example Code

The above steps are marked in the source code as comments.

@UnitTest
public class KeywordFillingJobTest
{
  @InjectMocks
  private KeywordFillingJob keywordFillingJob = new KeywordFillingJob(); //Class to test.
  (...)  @Mock
  private ArtikellisteModel artikelliste; // #1 Mock Model
 
  private String lastKeywords = null; // #2 Field to save the value sent as parameter to the mock model.
 
  @Test
  public void articleListWithCategories() {
    PerformResult result = this.keywordFillingJob.perform(conjobModel);
 
    Assert.assertEquals("The cronjob must be successful", CronJobResult.SUCCESS, result.getResult());
    Assert.assertEquals("The cronjob must be finished", CronJobStatus.FINISHED, result.getStatus());
    Assert.assertEquals("The generated keywords are wrong", EXPECTED_KEYWORDS, this.lastKeywords); // #4 Assert the value.
 
    Mockito.verify(this.modelService, Mockito.times(1)).save(this.artikelliste);
  }
 
  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this); // The mock model is created at this point.
    (...)
 
    Mockito.when(artikelliste.getName()).thenReturn("XYZ");
 
    Mockito.doAnswer(new Answer<Void>()
    {
      @Override public Void answer(final InvocationOnMock invocation) throws Throwable
      {
        lastKeywords = (String) invocation.getArguments()[0];
        return null;
      }
    }).when(artikelliste).setStichwoerter(Mockito.anyString()); //#3 Mock the setter to save the parameter in your field.
  }
}

Alternative: usage of capture arguments

Using Mockito ArgumentCaptor

–Based on Hybris 4.8.12

Discussion

Enter your comment. Wiki syntax is allowed: