Skip to content

Instantly share code, notes, and snippets.

@vkhorikov
Last active March 21, 2018 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vkhorikov/64ff397721cf40cf879c56d8f85ef57e to your computer and use it in GitHub Desktop.
Save vkhorikov/64ff397721cf40cf879c56d8f85ef57e to your computer and use it in GitHub Desktop.
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