2

I've got a piece of code like this:

    class Lekcja {
        Calendar _date;
        public Lekcja() {
            _date = Calendar.getInstance();
        }
        public Calendar getDate() {
            return _date;
        }
    }

And I want to test it using JUnit4 and Mockito, instead of using real Calendar object I want to put a mock object there. Could you please tell me how to do it?

reevesy
  • 3,452
  • 1
  • 26
  • 23
Wojciech Reszelewski
  • 2,656
  • 2
  • 18
  • 27
  • Technically you can do this kind of mocking using PowerMock, but you really should go with Tomasz answer. – Jens Schauder Jun 01 '12 at 08:00
  • Don't test this class. It doesn't have any logic, so there's no potential for logic errors, and therefore no benefit to having tests for it. Spend your time on something different, seriously. – Dawood ibn Kareem Jun 04 '12 at 03:07

2 Answers2

2

Mocking value objects is rarely a good idea. You should mock behaviour, not data. I guess what you really want to achieve is to be able to use arbitrary date in tests (which is a good idea).

The pattern I am using successfully in such cases is a fake system clock (examples from that site):

public interface TimeSource {
  long currentTimeMillis();
} 

And two implementations, real:

public final class RealSource implements TimeSource {

  public long currentTimeMillis() {
    return System.currentTimeMillis();
  }

}

and fake for testing:

public final class FakeSource implements TimeSource {

  public long currentTimeMillis() {
    return //...whatever you want
  }

}

I find it convenient to make currentTimeMillis() static in a helper method and use static field pointing to current TimeSource.

Finally, much simpler approach is to pass the date directly:

class Lekcja {
    Calendar _date;
    public Lekcja(Calendar date) {
        this._date = date;
    }
    //...
}

See also

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

You could use PowerMock

@RunWith(PowerMockRunner.class)
@PrepareForTest(Calendar.class)
public class LekcjaTest {
    private Lekcja lekcja;
    private Date myDate;

    @Before
    public void setUp() {
        myDate = mock(Date.class);

        PowerMockito.mockStatic(Calendar.class);
        PowerMockito.when(Calendar.getInstance()).thenReturn(myDate);
    }

    @Test
    public void calendarTest() {
        lekcja = new Lekcja();

        //verifies that the static call has been made
        PowerMockito.verifyStatic();
        Calendar.getInstance();

        assertEquals(myDate, lekcja.getDate());
    }
}
Tobb
  • 11,850
  • 6
  • 52
  • 77