No way to compare objects for similarity
wolever opened this issue · 5 comments
Unless I'm mistaken, there is no way to compare objects (ie, ObjectUtil.compare).
For example, this will fail:
assertThat({ foo: 42 }, equalTo({ foo: 42 }));
And there is no way to produce the expected result.
Err, sorry for the double-submit... Apparently GitHub isn't validating their forms properly :P
nw, I have added a couple of matchers recently that probably do what you want. Have a look at the hasProperty() and hasProperties() matchers.
assertThat({ foo: 42 }, hasProperty('foo', equalTo(42));
assertThat({ foo: 42 }, hasProperties({ foo: 42 });
assertThat({ foo: 42 }, hasProperties({ foo: equalTo(42) });
assertThat({ foo: 42 }, hasProperties({ foo: between(40, 45) });
The reason for the separate matcher is because equalTo is for shallow matches against typically primitives or by object reference. When you need the deep checking there is usually a more specific matcher that you can use.
Both the hasProperty() and hasProperties() matchers can take another matcher to match the value so you can nest the checks as deep as you want.
assertThat({ foo: { bar: { baz: 42 } } }, hasProperty('foo', hasProperty('bar', hasProperty('baz', equalTo(42));
In the vein of above I've been considering adding another matcher to match against a property chain. Let me know if the example below would be useful.
assertThat({ foo: { bar: { baz: 42 } } }, hasPropertyChain('foo.bar.baz', equalTo(42));
Also ObjectUtil.compare() is for comparisons as you would use for sorting, it results in -1, 0, 1, not true or false as Matcher.match() does. If you would like to use hamcrest for comparisons could you outline how you might like to use it in this scenario.
cheers,
Drew
Thanks a lot, Drew! hasProperties is exactly what I'm looking for (although the reason I couldn't find it is that I've been using an older version and didn't think to pull
before I checked).
Maybe it would be useful to add a 'common uses' or 'additions to normal hamcrest' section in the README to make this function (and the others which are probably like it) more discoverable?
If you're interested, I'll write it up.
(and, no, I don't want to use hamcrest for comparisons – just testing equality)
We'll probably find that the hamcrest-as3 matchers will diverge from the Java ones as the get tailored towards the usage patterns, naming conventions and language/VM features of Flash & Flex.
That would be awesome if you could write up a section for the README for the common cases like equalTo(), hasProperty(), hasProperties().
I have just pushed another update tonight, and also started adding content to the the wiki. The next big task is getting the ASDocs generated and up here as they are fairly thorough.