[NoBrainer] Mocking DateTimeOffset and DateTime with Telerik JustMock return unexpected values

Today’s post goes rather quick … Telerik JustMock in its commercial (i.e. non-free) version provides you the option to mock static classes, which comes in really handy when you want to mock something like DateTimeOffset. However, in our scenario it yielded some surprising results…

In my project I needed to mock a DateTimeOffset to have a sut (subject under test) calculate some relative dates from Now. At the same time, I wanted to assure that DateTimeOffset was called in all instances and NOT DateTime. So I created this mock:

[TestMethod]
public void GettingNextScheduleForScheduledJobReturnsExpectedDate()
{
  // Arrange
  var now = DateTimeOffset.Parse("2019-04-13 08:15:42+02:00");
  var expectedSchedule = DateTimeOffset.Parse("2019-04-13 18:00:00+02:00");

  Mock.SetupStatic(typeof(DateTimeOffset), Behavior.Loose);
  Mock.Arrange(() => DateTimeOffset.Now)
    .Returns(now)
    .MustBeCalled();

  Mock.SetupStatic(typeof(DateTime), Behavior.Loose);
  Mock.Arrange(() => DateTime.Now)
    .OccursNever();

  var job = new ScheduledJob()
  {
    Crontab = "* 18 * * *"
  };
  var sut = new ScheduledJobScheduler(job);

  // Act
  var result = sut.GetNextSchedule();

  // Assert
  Mock.Assert(() => DateTime.Now);
  Mock.Assert(() => DateTimeOffset.Now);
  Assert.AreEqual(expectedSchedule, result);
}

However the code in GetNextSchedule falsely returned DateTimeOffset.MinValue when calling DateTimeOffset.Now as you can see from this screenshot:

JustMock DateTimeOffset

JustMock DateTimeOffset

After some investigation I found out that the call to set up the static mock for DateTime was the cause of the problem:

Mock.SetupStatic(typeof(DateTime), Behavior.Loose);

As it seemed DateTimeOffset is internally relying on DateTime and the Behavior.Loose also applied to the constructor (as we did not specifically arrange that). So the solution was to simply delete that statement.

So in reality it was not really a problem of JustMock rather than using it in a wrong way. And with that we are at the end of our today’s story.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: