chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
I'd like to write unit tests that simulates the system clock being changed, but I am getting odd results when faking DateTime.UtcNow. If I perform the following:

Isolate.WhenCalled(() => DateTime.UtcNow).DoInstead(ctx => DateTime.UtcNow.AddMinutes(20));
Debug.WriteLine(DateTime.UtcNow);


Instead of advancing UtcNow by 20 minutes, it is advanced by 40 minutes. What am I doing wrong?
asked by allon.guralnek (10.6k points)

2 Answers

0 votes
Hi Allon,

We don't yet support the feature which would allow you to replace a method with a different call of the same method.

What you can do instead is create a sequence which will simulate the clock change like this:

DateTime dt20 = DateTime.UtcNow.AddMinutes(20);
DateTime dt40 = DateTime.UtcNow.AddMinutes(40);
DateTime dt60 = DateTime.UtcNow.AddMinutes(60);

Isolate.WhenCalled(() => DateTime.UtcNow).WillReturn(dt20);
Isolate.WhenCalled(() => DateTime.UtcNow).WillReturn(dt40);
Isolate.WhenCalled(() => DateTime.UtcNow).WillReturn(dt60);

Debug.WriteLine(DateTime.UtcNow);
Debug.WriteLine(DateTime.UtcNow);
Debug.WriteLine(DateTime.UtcNow); 


This feature is now in our backlog and it might be added in the future versions.

Regards,
Alex,
Typemock Support.
answered by alex (17k points)
0 votes
I understand, thanks for the reply.

I think a good way to implement the feature is by having the context object, in addition to having the original arguments the instance object, have a method called object CallOriginal(params object[]) which would allow calling the unfaked method. For faking instance members, you can even provide a reference to the underlying unfaked object, so that the .DoInstead() lambda can use several unfaked methods even if they were previously faked, e.g.:

var fake = Isolate.Fake.Instance<MyClass>();
Isolate.WhenCalled(() => fake.Foo())
       .DoInstead(ctx => ctx.UnfakedInstance.Foo() + ctx.UnfakedInstance.Bar());


This will mean that ctx will have to be a generic class so that UnfakedInstance would be of the correct type.
answered by allon.guralnek (10.6k points)
...