.st0{fill:#FFFFFF;}

How OCHamcrest’s “hasProperty” Can Make Your Tests Simpler 

 October 12, 2011

by Jon Reid

4 COMMENTS

Whenever test code has repeated patterns, there’s an opportunity to make it more expressive and readable. This can sometimes be done by creating a new OCHamcrest matcher.

OCHamcrest features a great new matcher submitted by Justin Shacklette: hasProperty.

“hasProperty” is something of a misnomer, because it’s not just for properties. Any method, without arguments, that returns an object, is fair game. But I couldn’t think of a better name; I think it communicates well. Let’s take a look at a before-and-after code example.

Before “hasProperty”

A little before-and-after may show you why I’m so excited about this matcher. Here’s a test I wrote before OCHamcrest 1.6:

- (void)testArrayFromURLStringArray
{
    // given
    NSArray *URLStrings = [NSArray arrayWithObjects:@"one", @"two", nil];
    // when
    NSMutableArray *downloads = [MyDownloader arrayFromURLStringArray:URLStrings];
    // then
    assertThat(downloads, hasCountOf(2));
    MyDownloader *download = [downloads objectAtIndex:0];
    assertThat([download URLString], is(@"one"));
    download = [downloads objectAtIndex:1];
    assertThat([download URLString], is(@"two"));
}

As you can see, the test creates an array of two strings. It passes this array to the method under test, a convenience method that creates an array of MyDownloader objects. The expectation is that the resulting array will have URLString values matching the original array of strings.

What I don't like about this test is that the verification has to go through a number of steps:

  • Confirm that the resulting array has a count of 2.
  • Get the first element.
  • Confirm its URLString value.
  • Get the second element.
  • Confirm its URLString value.

After “hasProperty”

Enter the OCHamcrest 1.6 “hasProperty” matcher! Now the same test can be rewritten as follows:

- (void)testArrayFromURLStringArray
{
    // given
    NSArray *URLStrings = [NSArray arrayWithObjects:@"one", @"two", nil];
    // when
    NSMutableArray *downloads = [MyDownloader arrayFromURLStringArray:URLStrings];
    // then
    assertThat(downloads, contains(hasProperty(@"URLString", @"one"),
                                   hasProperty(@"URLString", @"two"),
                                   nil));
}

The “contains” matcher matches an array, in order, with the given matchers. That’s not new. What’s new is the ability to use “hasProperty” to say, “Call a method with this name. Does its return value match the second argument?”

“hasProperty” Takes Another Matcher

In this example, the second arguments of the two “hasProperty” matchers are strings. But as with many other matchers, the argument can also be another matcher. For example,

hasProperty(@"URLString", startsWith(@"https://"))

will match if the URLString value starts with "https://"—a simple way to confirm that you’re using a secure connection.

“hasProperty” with Mock Objects

I’ve also found that “hasProperty” simplifies tests that use mock objects. Say you want to verify that a method is invoked with an argument having certain properties. I used to have to extract the argument from the mock object, then call the argument to get the property of interest, then verify the value of that property. No more! Now I just set up the mock object’s expectation with a “hasProperty” matcher.

New in OCHamcrest 1.6

So there you have it: The “hasProperty” matcher is new in OCHamcrest 1.6, and will simplify your tests. This latest version also checks that matchers that take nil-terminated lists (like “contains”) actually end with nil—which used to be an easy mistake to make. Download OCHamcrest 1.6 today!

See also: Hamcrest: A Tool for Readable, Powerful Unit Tests

Question: What other repeated patterns do you encounter in test code? Leave a comment below.

Jon Reid

About the author

Programming was fun when I was a kid. But working in Silicon Valley, I saw poor code lead to fear, with real human costs. Looking for ways to make my life better, I learned about Extreme Programming, including unit testing, test-driven development (TDD), and refactoring. Programming became fun again! I've now been doing TDD in Apple environments for 20 years. I'm committed to software crafting as a discipline, hoping we can all reach greater effectiveness and joy. Now a coach with Industrial Logic!

    • Jasper,
      It could have been a selector, I suppose. Looking back, I’m not sure why I chose to use a string except maybe that it makes TDD a little easier. But I don’t mind having to update tests to match, as long as the change is centralized.

  • There is a mistake in the first code snippet, the variable is declared as “download” while it is called as “image” when using.

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
    >