Create a gist now

Instantly share code, notes, and snippets.

@vkhorikov /1.cs
Last active Mar 21, 2018

Embed
What would you like to do?
Non-determinism in tests
public class SomeService
{
public void FirePeriodicJob()
{
/* Runs asynchronously */
}
}
[Fact]
public void Test()
{
var sut = new SomeService();
sut.FirePeriodicJob();
// Give the job time to complete
Thread.Sleep(10000);
/* Verify the effects of the job */
}
[Fact]
public void Test()
{
var sut = new SomeService();
sut.FirePeriodicJob();
// Give the job time to complete
Task.Delay(10000).Wait();
/* Verify the effects of the job */
}
[Fact]
public void Test()
{
var sut = new CustomerService();
Customer customer = sut.Create("Name");
Assert.Equal(DateTime.Now, customer.DateCreated);
}
[Fact]
public void Test()
{
DateTime now = DateTime.Now;
var sut = new CustomerService();
Customer customer = sut.Create("Name", now);
Assert.Equal(now, customer.DateCreated);
}
public static class SystemDateTime
{
    private static Func<DateTime> _func;
 
    public static DateTime Now
    {
        get { return _func(); }
    }
 
    public static void Init(Func<DateTime> func)
    {
        _func = func;
    }
}
// Initialization code for production
SystemDateTime.Init(() => DateTime.UtcNow);
// Initialization code for unit tests
SystemDateTime.Init(() => new DateTime(2016, 10, 3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment