我正在尝试比较两个对象,看看它们是否相同,使用 hamcrest 作为 flex-unit,但是当对象有子对象时,它只会抛出一个错误:
Error: Expected: (An array containing <[object Object]>
but: an array containing <[object Object]> was <[object Object]>
我希望它做一个 assertThat(..., hasProperties(...)); 在子对象上。
有没有办法得到它或者我应该创建一个自定义匹配器?
编辑
我想测试的对象结构的一个例子:
var expected:Object = {
number:1.3,
array:[{
prop1:"val1", prop2:"val2"
}]
anObject:{
propA:1, propB:2
},
}
var objectUnderTest:Object = {
number:1.3,
array:[{
prop1:"val1", prop2:"val2"
}]
anObject:{
propA:1, propB:2
},
}
assertThat("should be the same", objectUnderTest, hasProperties(expected));
由于预期和 objectUnderTest 具有相同的结构,测试应该通过,但返回错误:
Error: Expected: (An array containing <[object Object]>
but: an array containing <[object Object]> was <[object Object]>
此外,如果有办法比较两个 JSON 字符串也可以。
编辑2
这是我在 djib 帮助后的最终版本:
package com
{
public function assertEqualsObjects(message:String, object1:Object, object2:Object):Boolean
{
// we have to run it both ways (1-2, 2-1)
return (compare(object1, object2, message + ": object") && compare(object2, object1, message + ": extra"));
}
}
import org.flexunit.asserts.fail;
function compare(object1:Object, object2:Object, parent:String):Boolean
{
var count:int = 0;
for (var s:String in object1)
{
count ++;
if (!object2.hasOwnProperty(s))
{
fail(parent + "." + s + " expected: " + object1[s] + " but was: undefined");
return false;
}
if (!compare(object1[s], object2[s], parent + "." + s))
{
fail(parent + "." + s + " expected: " + object1[s] + " but was: " + object2[s]);
return false;
}
}
if (count == 0 && object1 != object2) // if object has no properties, compare their actual values
{
fail(parent + " expected: " + object1 + " but was: " + object2);
return false;
}
return true;
}