在我的单元测试中,使用NUnit,我试图使用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);
}
它工作正常,但对于DateTime,它引发此错误的属性
String lengths are both 498. Strings differ at index 65.
Expected: "...onDateTime":"\\/Date(1410857388258)\\/","TransactionID":"Tra..."
But was: "...onDateTime":"\\/Date(1410857388000)\\/","TransactionID":"Tra..."
---------------------------------------------^
我正在使用的代码是
[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);
}
被
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;
}
在进入AreEqualByJson之前,日期是相同的,但是当它们被序列化时,我得到了这个偏移量,这使得我的测试失败了。
是否有错误或者我应该将所有日期视为AreEqualByJson中的特定情况(仍然将其作为可重用的方法维护)?
谢谢,
更新
根据Marc Gravell的评论,我最终在CreateTargetDecisionResponse中做了这个
TransactionDateTime = DateTime.Parse(now.ToString(" yyyy-MM-ddThh:mm:sss"))
答案 0 :(得分:0)
对象1,TransactionDateTime = now.ToString("yyyy-MM-ddThh:mm:sss")
(假设FromResponseToDecisionResponse
正在将字符串转换回DateTime)
对象2,TransactionDateTime = now,
如果两者结果相同,那只能是巧合......即当now
没有任何小数秒时......
这是测试中最明显不正确的部分。