Created
August 31, 2017 10:24
-
-
Save vincelee888/c196c73e29d0028d81caebb2e8450a60 to your computer and use it in GitHub Desktop.
NUnit assertion for DateTime comparison
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using NUnit.Framework.Constraints; | |
namespace Foundation.Testing.Assertions | |
{ | |
public sealed class DateTimeIsApproximatelyConstraint : Constraint | |
{ | |
private readonly DateTime _upper; | |
private readonly DateTime _lower; | |
public DateTimeIsApproximatelyConstraint(DateTime expected, int toleranceInMs = 1000) | |
{ | |
_lower = expected.AddMilliseconds(-toleranceInMs); | |
_upper = expected.AddMilliseconds(toleranceInMs); | |
this.Description = $" to be between {_lower} and {_upper}"; | |
} | |
public override ConstraintResult ApplyTo<TActual>(TActual actual) | |
{ | |
var actualAsDateTime = actual as DateTime?; | |
var passes = actualAsDateTime != null && (actualAsDateTime.Value >= _lower && actualAsDateTime.Value <= _upper); | |
return new ConstraintResult(this, actual, passes); | |
} | |
} | |
public static class DateTimeIsApproximatelyConstraintExtensions | |
{ | |
public static DateTimeIsApproximatelyConstraint Approximately(this ConstraintExpression expression, DateTime expected, int toleranceInMs = 1000) | |
{ | |
var constraint = new DateTimeIsApproximatelyConstraint(expected, toleranceInMs); | |
expression.Append(constraint); | |
return constraint; | |
} | |
} | |
public class Is : NUnit.Framework.Is | |
{ | |
public static DateTimeIsApproximatelyConstraint Approximately(DateTime expected, int toleranceInMs = 1000) | |
{ | |
return new DateTimeIsApproximatelyConstraint(expected, toleranceInMs); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment