为什么 Assert.AreEqual(T obj1, Tobj2) 会因相同的字节数组而失败
我在以下代码段中有两个相同的字节数组:
/// <summary>
///A test for Bytes
///</summary>
[TestMethod()]
public void BytesTest() {
byte[] bytes = Encoding.UTF8.GetBytes(Properties.Resources.ExpectedPacketData);
TransferEventArgs target = new TransferEventArgs(bytes);
byte[] expected = Encoding.UTF8.GetBytes(Properties.Resources.ExpectedPacketValue);
byte[] actual;
actual = target.Bytes;
Assert.AreEqual(expected, actual);
}
两个数组在每个字节上都是相同的。在这种情况下,为什么 Assert.AreEqual 会失败?
I have two identical byte arrays in the following segment of code:
/// <summary>
///A test for Bytes
///</summary>
[TestMethod()]
public void BytesTest() {
byte[] bytes = Encoding.UTF8.GetBytes(Properties.Resources.ExpectedPacketData);
TransferEventArgs target = new TransferEventArgs(bytes);
byte[] expected = Encoding.UTF8.GetBytes(Properties.Resources.ExpectedPacketValue);
byte[] actual;
actual = target.Bytes;
Assert.AreEqual(expected, actual);
}
Both arrays are identical down to the very byte. In this scenario, why would Assert.AreEqual fail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Assert.Equals
使用Equals
方法进行测试,该方法默认使用引用相等,并且由于它们是不同的对象,因此它们不相等。您需要比较数组中的每个字节并验证它们是否相等。一种方法是将它们转换为实现 ICollection 的内容并使用 CollectionAssert.AreEqual() 代替。Assert.Equals
tests using theEquals
method, which by default uses reference equality and, since they are different objects, they are not equal. You'll want to compare each byte in the array and verify that they are equal. One way to do this is convert them to something that implements ICollection and use CollectionAssert.AreEqual() instead.因为数组不会覆盖
Equals
。您还没有说明您正在使用哪个测试框架,但基本上这取决于该框架对特殊情况数组的影响。当然,您始终可以实现自己的辅助方法来做到这一点。我有时也这么做过。对于快速而肮脏的黑客攻击,如果您使用 .NET 3.5,则可以使用
Enumerable.SequenceEqual
扩展方法:当然,自定义帮助器方法可以为您提供有关它们之间差异的更多详细信息。您可能会在
MoreLINQ 中找到这些方法。 TestExtensions
很有帮助,尽管它们也相当粗糙且准备就绪。Because arrays don't override
Equals
.You haven't said which test framework you're using, but basically it would be up to that framework to special-case arrays. You can always implement your own helper method to do that, of course. I've done that sometimes. For a quick and dirty hack, if you're using .NET 3.5 you can use the
Enumerable.SequenceEqual
extension method:A custom helper method could give you more details about how they differ, of course. You might find the methods in
MoreLINQ.TestExtensions
helpful, although they're fairly rough and ready too.对于非空值,底层的 Assert.AreEqual 方法最终将默认为 Object.Equals()。 Object.Equals() 的默认实现是引用相等。这两个数组在值方面相同,但在引用方面不同,因此不会被视为相等。
The method Assert.AreEqual under the hood will end up defaulting to Object.Equals() for non-null values. The default implementation of Object.Equals() is referential equality. The 2 arrays are identical value wise but difference reference wise and hence will not be considered equal.
创建了简单的辅助方法:
Created simple helper method:
会比较这些东西...它对我有用..
will compare the stuff... It works for me..