The OCHamcrest TutorialIntroductionOCHamcrest is an Objective-C framework for writing matcher objects allowing 'match' rules to be defined declaratively. There are a number of situations where matchers are invaluble, such as UI validation, or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used. This tutorial shows you how to use OCHamcrest for unit testing. When writing tests it is sometimes difficult to get the balance right between overspecifying the test (and making it brittle to changes), and not specifying enough (making the test less valuable since it continues to pass even when the thing being tested is broken). Having a tool that allows you to pick out precisely the aspect under test and describe the values it should have, to a controlled level of precision, helps greatly in writing tests that are "just right". Such tests fail when the behaviour of the aspect under test deviates from the expected behaviour, yet continue to pass when minor, unrelated changes to the behaviour are made. My first OCHamcrest testNote: To use OCHamcrest in an Xcode unit test bundle, you may need to add a "Copy Files" build phase which copies OCHamcrest.frameworks to the Products directory. We'll start be writing a very simple Xcode unit test, but instead of using SenTestingKit's STAssertEqualObjects method, we use OCHamcrest's assertThat construct and the standard set of matchers. #import <SenTestingKit/SenTestingKit.h>
#define HC_SHORTHAND
#import <OCHamcrest/OCHamcrest.h>
@interface BiscuitTest : SenTestCase
@end
@implementation BiscuitTest
- (void) testEquals
{
Biscuit* theBiscuit = [Biscuit biscuitNamed:@"Ginger"];
Biscuit* myBiscuit = [Biscuit biscuitNamed:@"Ginger"];
assertThat(theBiscuit, equalTo(myBiscuit));
}
@endThe assertThat method is a stylized sentence for making a test assertion. In this example, the subject of the assertion is the object biscuit that is the first method parameter. The second method parameter is a matcher for Biscuit objects, here a matcher that checks one object is equal to another using the isEqual: method. The test passes since the Biscuit class defines an isEqual: method. OCHamcrest's functions are actually declared with an HC_ package prefix (such as HC_assertThat and HC_equalTo) to avoid name clashes. To make test writing faster and test code more legible, shorthand macros are provided if HC_SHORTHAND is defined before including the OCHamcrest header. These macros omit the package prefix; for example, instead of writing HC_assertThat one can simply write assertThat. A tour of common matchersOCHamcrest comes with a library of useful matchers. Here are some of the most important ones. - Core
- anything - always matches, useful if you don't care what the object under test is
- describedAs - decorator to adding custom failure description
- is - decorator to improve readability - see "Syntactic sugar", below
- Logical
- allOf - matches if all matchers match, short circuits (like C's &&)
- anyOf - matches if any matchers match, short circuits (like C's ||)
- isNot - matches if the wrapped matcher doesn't match and vice versa
- Object
- equalTo - test object equality using -isEqual:
- hasDescription - test -description
- instanceOf, isCompatibleType - test type
- notNilValue, nilValue - test for nil
- sameInstance - test object identity
- Collections
- hasEntry, hasKey, hasValue - test an NSDictionary contains an entry, key or value
- hasItem, hasItems - test a collection contains elements
- Number
- closeTo - test floating point values are close to a given value
- greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo - test ordering
- Text
- equalToIgnoringCase - test string equality ignoring case
- equalToIgnoringWhiteSpace - test string equality ignoring differences in runs of whitespace
- containsString, endsWith, startsWith - test string matching
Syntactic sugarOCHamcrest strives to make your tests as readable as possible. For example, the is matcher is a wrapper that doesn't add any extra behavior to the underlying matcher. The following assertions are all equivalent: assertThat(theBiscuit, equalTo(myBiscuit));
assertThat(theBiscuit, is(equalTo(myBiscuit)));
assertThat(theBiscuit, is(myBiscuit)); The last form is allowed since is(id item) wraps non-matcher arguments with equal_to. Writing custom matchersOCHamcrest comes bundled with lots of useful matchers, but you'll probably find that you need to create your own from time to time to fit your testing needs. This commonly occurs when you find a fragment of code that tests the same set of properties over and over again (and in different tests), and you want to bundle the fragment into a single assertion. By writing your own matcher you'll elimate code duplication and make your tests more readable! Let's write our own matcher for testing if a calendar date falls on a Saturday. This is the test we want to write: - (void) testDateIsOnASaturday
{
NSCalendarDate* date = [NSCalendarDate dateWithString:@"26 Apr 2008" calendarFormat:@"%d %b %Y"];
assertThat(date, is(onASaturday()))
}Here's the interface: #import <OCHamcrest/HCBaseMatcher.h>
@interface IsGivenDayOfWeek : HCBaseMatcher
{
NSInteger day; // 0 indicates Sunday
}
+ (IsGivenDayOfWeek*) isGivenDayOfWeek:(NSInteger)dayOfWeek;
- (id) initWithDay:(NSInteger)dayOfWeek;
@end
#ifdef __cplusplus
extern "C" {
#endif
id<HCMatcher> HC_onASaturday();
#ifdef __cplusplus
}
#endif
#ifdef HC_SHORTHAND
#define onASaturday HC_onASaturday
#endifThe interface consists of three parts: a class definition, a factory function (with C binding), and a shorthand macro. Here's what the implementation looks like: #import "IsGivenDayOfWeek.h"
#import <OCHamcrest/HCDescription.h>
@implementation IsGivenDayOfWeek
+ (IsGivenDayOfWeek*) isGivenDayOfWeek:(NSInteger)dayOfWeek;
{
return [[[IsGivenDayOfWeek alloc] initWithDay:dayOfWeek] autorelease];
}
- (id) initWithDay:(NSInteger)dayOfWeek;
{
self = [super init];
if (self != nil)
day = dayOfWeek;
return self;
}
- (BOOL) matches:(id)item
{
if (![item respondsToSelector:@selector(dayOfWeek)])
return NO;
return [item dayOfWeek] == day;
}
- (void) describeTo:(id<HCDescription>)description;
{
NSString* dayAsString[] =
{@"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday"};
[[description appendText:@"calendar date falling on "]
appendText:dayAsString[day]];
}
@end
extern "C" {
id<HCMatcher> HC_onASaturday()
{
return [IsGivenDayOfWeek isGivenDayOfWeek:6];
}
} // extern "C"
For our Matcher implementation we implement the matches: method - which calls the dayOfWeek method after confirming that the argument has such a method - and the describe_to method - which is used to produce a failure message when a test fails. Here's an example of how the failure message looks: NSCalendarDate* date = [NSCalendarDate dateWithString: @"6 April 2008"
calendarFormat: @"%d %B %Y"];
assertThat(date, is(onASaturday()));fails with the message Expected: is calendar date falling on Saturday, got: <06 April 2008> and Xcode shows it as a build error. Double clicking the error message takes you to the assertion that failed. Even though the HC_onASaturday function creates a new matcher each time it is called, you should not assume this is the only usage pattern for your matcher. Therefore you should make sure your matcher is stateless, so a single instance can be reused between matches.
|