OCHamcrestExtensions is built on top of OCHamcrest. It adds several more features, including:
- Support for exception assertions.
- More matchers.
OCHamcrestExtensions is a drop in replacement but does contain all the source code of the original OCHamcrest project. If you try and link both libraries you will get duplicate symbol errors.
Below is only documentation for the additions, refer to the OCHamcrest documentation for everything else.
Add the following dependency to your Podfile. Most people will want OCHamcrest in their test targets, and not include any pods from their main targets:
target :MyTests, :exclusive => true do
pod 'OCHamcrestExtensions', '~> 1.0'
end
Use the following import:
#define HC_SHORTHAND
#import <OCHamcrestExtensions/OCHamcrestExtensions.h>
OCHamcrest comes with a library of useful matchers. This list contains only the additions for OCHamcrestExtensions.
-
Boolean
assertYes
- convienience method forassertThatBool(x, equalToBool(YES))
assertNo
- convienience method forassertThatBool(x, equalToBool(NO))
assertTrue
- same asassertYes
assertFalse
- same asassertNo
-
Text
emptyString
- match an empty string
-
Exception
ignoringReturnValue
- used to wrap expressions of non-id
return typewillThrow
- assert that a specific NSException is thrown is thrownwillThrowException
- assert that any NSException is thrownwillNotThrowException
- assert that no exception is thrown
Checking if an exception was thrown (or not thrown) works much the same way as general assertions:
assertThat([myObject mightThrowException], willThrowException());
assertThat([myObject mightThrowException], willNotThrowException());
Asserting specific names:
assertThat([myObject mightThrowException], willThrow(NSInvalidArgumentException));
Dealing with void and other non-id
related expressions:
assertThat(ignoringReturnValue(1 + 1), willNotThrowException());
Using string matchers against the exception reason:
NSException *e = [NSException exceptionWithName:NSInvalidArgumentException
reason:@"For fun."
userInfo:nil];
assertThat(ignoringReturnValue(@throw e), allOf(
willThrow(NSInvalidArgumentException),
containsString(@"fun."),
nil
));
You do not have to specify the exception assertion, so the above could be written shorter - however if the expression returned a string containing "fun." and did not throw then this would be a false-positive:
assertThat(ignoringReturnValue(@throw e), containsString(@"fun."));
A safer way and easier way to assert the precise exception with message is to use equality since it contains both:
assertThat(ignoringReturnValue(@throw e), equalTo(@"NSInvalidArgumentException: For fun."));