Link to home
Start Free TrialLog in
Avatar of Valimai
Valimai

asked on

Unit test failing because of millisecond compare on (DateTime?) nullable type (.NET 2.0)

Hi,

I have an assert
Assert.AreEqual(savedUser.DateCreated, loadUser.DateCreated, "DateCreated");

The problem is that it fails because loading up from SQL changes the value of the milliseconds (i know why).
My question is, how do i compare dates?
Note: User.DateCreated is type (DateTime?), nullable

ORIGINAL ASSERT
Assert.AreEqual(savedUser.DateCreated, loadUser.DateCreated, "DateCreated");
ERROR
Test_UserData.Load :   DateCreated
  Expected: 2007-10-11 08:51:01.638
  But was:  2007-10-11 08:51:01.640

NEXT ATTEMPT
Assert.AreEqual(savedUser.DateCreated.Value.ToString("yyyymmnn H:nn:ss"), loadUser.DateCreated.Value.ToString("yyyymmnn H:nn:ss"), "DateCreated");
ERROR
Test_UserData.Load : System.InvalidOperationException : Nullable object must have a value.

That is because DateCreated is null.

How do i compare without the millisecond component in an efficient manner?

thanks
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

If you are working with a Nullable type, then I would check that DateCreated has a value before asserting that the values are equal.

Bob
Avatar of Valimai
Valimai

ASKER

ok, i ended up doing this for each of my dates. 4 in this object.

CompareNullableDate(savedUser.DateCreated, loadUser.DateCreated, "DateCreated");

private static void CompareNullableDate(DateTime? expectedDate, DateTime? compareDate, string fieldName)
{
      if (expectedDate == null)
      {
            Assert.IsNull(expectedDate);
      }
      else
      {
            Assert.AreEqual(expectedDate.Value.ToString("yyyymmnn H:nn:ss"), compareDate.Value.ToString("yyyymmnn H:nn:ss"), fieldName);
      }
}
Avatar of Valimai

ASKER

changed
Assert.IsNull(expectedDate, fieldName);
Avatar of Valimai

ASKER

whoops, i meant
Assert.IsNull(compareDate, fieldName);
ASKER CERTIFIED SOLUTION
Avatar of dstanley9
dstanley9

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial