We help IT Professionals succeed at work.

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

Valimai
Valimai asked
on
447 Views
Last Modified: 2008-01-09
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
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2008

Commented:
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

Author

Commented:
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);
      }
}

Author

Commented:
changed
Assert.IsNull(expectedDate, fieldName);

Author

Commented:
whoops, i meant
Assert.IsNull(compareDate, fieldName);
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.