In my unit tests, using NUnit, I'm trying to compare the equality of two objects using this answer
public static void AreEqualByJson(object expected, object actual)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var expectedJson = serializer.Serialize(expected);
var actualJson = serializer.Serialize(actual);
Assert.AreEqual(expectedJson, actualJson);
}
It works fine but for a property which is DateTime where it raises this error
String lengths are both 498. Strings differ at index 65.
Expected: "...onDateTime":"\\/Date(1410857388258)\\/","TransactionID":"Tra..."
But was: "...onDateTime":"\\/Date(1410857388000)\\/","TransactionID":"Tra..."
---------------------------------------------^
The code that I'm using for that is this
[Test]
public void FromResponseToDecisionResponse_MapsAllProperties()
{
//Arrange
var now = DateTime.Now;
var sourceResponse = CreateSourceResponse(now);
var targetDecisionResponse = CreateTargetDecisionResponse(now);
//Act
var mappedResponse = _mapper.FromResponseToDecisionResponse(sourceResponse);
//Assert
AreEqualByJson(targetDecisionResponse, mappedResponse);
}
Being
private static Response CreateSourceResponse(DateTime now)
{
var sourceResponse = new Response
{
//More properties
TransactionDateTime = now.ToString("yyyy-MM-ddThh:mm:sss")
};
return sourceResponse;
}
private static DecisionResponse CreateTargetDecisionResponse(DateTime now)
{
var targetDecisionResponse = new DecisionResponse
{
//Other properties
TransactionDateTime = now,
//More properties
};
return targetDecisionResponse;
}
Just before going into AreEqualByJson the dates are the same, but when they are serialized I got this offset that makes my test fail.
Is there something wrong or I should treat all dates as particular cases in AreEqualByJson (still maintaining it as a reusable method)?
Thanks,
UPDATE
As per Marc Gravell comment I ended up doing this in CreateTargetDecisionResponse
TransactionDateTime = DateTime.Parse(now.ToString("yyyy-MM-ddThh:mm:sss"))