The built-in matchers of Mockito cover most of the cases that you need in yours tests. However when using dates in them, you would need to compare them ignoring some fields like the seconds, minutes and hour. This can be elegantly accomplish with custom matchers.

Introduction

The test class calls a DAO which returns the historical price of a given date. The DAO ignores the seconds, minutes and hour before querying the database and our test class uses the current time and date as starting point for the calculation. This means that the date sent to the DAO depends on the current time on the machine.

The matcher

To write one is as simple as to implement ArgumentMatcher and return true only if the condition is met:

import de.hybris.platform.servicelayer.util.ServicesUtil;
import java.util.Calendar;
import org.mockito.ArgumentMatcher;

/**
 * Use this class to match calendar arguments of mock methods.
 * 
 */
public class DatePartOnlyCalendarMatcher extends ArgumentMatcher<Calendar>
{

  private final Calendar expectedDate;

  public DatePartOnlyCalendarMatcher(final Calendar anExpectedDate)
  {
    ServicesUtil.validateParameterNotNullStandardMessage("anExpectedDate", anExpectedDate);
    this.expectedDate = anExpectedDate;
  }

  @Override
  public boolean matches(final Object pArgument)
  {
    if (pArgument instanceof Calendar)
    {
      final Calendar actualDate = (Calendar) pArgument;

      return (this.expectedDate.get(Calendar.YEAR) == actualDate.get(Calendar.YEAR)
          && this.expectedDate.get(Calendar.MONTH) == actualDate.get(Calendar.MONTH)
          && this.expectedDate.get(Calendar.DAY_OF_MONTH) == actualDate.get(Calendar.DAY_OF_MONTH));
    }
    else
    {
      return false;
    }
  }
}

Using the matcher

The unit test uses the matcher in the following lines:

    final Calendar yesterday = Calendar.getInstance();
    yesterday.add(PriceTrendPeriod.DAY.getCalendarPeriod(), -1);
    final HistoricPriceModel historicalPriceYesterday = Mockito.mock(HistoricPriceModel.class);    
    Mockito.when(
        this.historicPriceDAO.getHistoricPrice(Matchers.eq(this.testProduct),
            Matchers.argThat(new DatePartOnlyCalendarMatcher(yesterday))))
        .thenReturn(historicalPriceYesterday);

 

Add comment


Security code
Refresh