Question

Say I want to assert that two structs are equivalent:

// Using CGPoint here for brevity, but my question applies to any struct type
CGPoint a = CGPointMake(1, 2);
CGPoint b = CGPointMake(1, 2);
STAssertEquals(a, b, @"this works");
assertThat(a, equalTo(b));

Is there no way to write an assertion using Hamcrest that works like the STAssertEquals above? The assertThat line fails to compile as the macros expect id parameters, which structs are not. I tried variations of the equalTo matcher, such as sameInstance, but they all seem to require id typed parameters. Next, I thought a good workaround would be to assert that an arbitrary expression has a YES or NO value. Something like this:

assertThat(a == b);

or this:

assertThat(a == b, isTrue());

But I don't see anything like this in Hamcrest.

Am I am missing something obvious? Clearly I can accomplish what I want to do by using the SenTest macros such as STAssertEquals, but I had expected it to be simple to implement these assertions using Hamcrest, so that all my assertions have a consistent style.

I also know that I can do this by implementing a custom Hamcrest matcher for the particular structs I am comparing. But I was really looking for a simple assertion/matcher that can just compare any C structs for simple bytewise equality.

Perhaps it's simply the case that none of the possibilities I have mentioned are possible out of the box with Hamcrest. If that's true, I'll accept a convincing explanation to this effect as the Answer.

Thanks

Was it helpful?

Solution

OCHamcrest is designed to check objects for matches, so assertThat takes an argument as the first parameter (and a matcher as the second).

There is limited support for scalars. For example, you can say

assertThatInteger(a, equalToInteger(b));

A change has been sent to me for an NSValue matcher, but I haven't had time to review it yet. It opens the door to NSPoint, NSSize, etc. But still, scalar support in OCHamcrest is a workaround.

For your own structs, I'd use STAssertEquals. The problem is that it's an all-or-nothing equality comparison, which may make your tests brittle. If that happens, it would be nicer to write your own custom matcher that supports per-field matching. (I'll try to make the NSValue matcher something you can subclass.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top