Giter Site home page Giter Site logo

hamcrest / ochamcrest Goto Github PK

View Code? Open in Web Editor NEW
712.0 712.0 100.0 10.2 MB

Hamcrest for Objective-C: Powerful, combinable, extensible matchers for verification

Home Page: http://hamcrest.org

License: BSD 2-Clause "Simplified" License

Objective-C 98.28% Ruby 0.52% Shell 0.94% Swift 0.26%
hamcrest objective-c testing xctest

ochamcrest's People

Contributors

actions-user avatar autoc0diq avatar bennettsmith avatar bryant1410 avatar chrispix avatar csano avatar dependabot[bot] avatar dflems avatar jacobsa avatar jonreid avatar klundberg avatar kmcbride avatar nschum avatar rhgills avatar sdefresne avatar sebastianludwig avatar todd1251 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ochamcrest's Issues

Binary 2.0.0: EXC_BAD_ACCESS when reporting assertion failure

Hi,

I get a EXC_BAD_ACCESS crash when I have failing asserts. I use the OCHamcrest 2.0.0 Mac binary, SENTest and Xcode 4.6.2.

I small "hello world" project is enough to produce the crash.

- (void)test {
    assertThat(@"foo", equalTo(@"bar"));
}

Here is the backtrace.

(lldb) bt
* thread #1: tid = 0x1e03, 0x00007fff92d0e710 libobjc.A.dylib`objc_msgSend_vtable13 + 16, stop reason = EXC_BAD_ACCESS (code=13, address=0x0)
frame #0: 0x00007fff92d0e710 libobjc.A.dylib`objc_msgSend_vtable13 + 16
frame #1: 0x00007fff8d514ca1 CoreFoundation`+[__NSDictionaryI __new:::::] + 545
frame #2: 0x00007fff8d44b281 CoreFoundation`-[__NSPlaceholderDictionary initWithObjects:forKeys:count:] + 289
frame #3: 0x00007fff8d465ac8 CoreFoundation`+[NSDictionary dictionaryWithObjectsAndKeys:] + 1000
frame #4: 0x000000010003f378 SenTestingKit`+[NSException(SenTestFailure) failureInFile:atLine:withDescription:] + 332
frame #5: 0x00007fff8d47a09c CoreFoundation`__invoking___ + 140
frame #6: 0x00007fff8d479f37 CoreFoundation`-[NSInvocation invoke] + 263
frame #7: 0x000000010005a8ce OCHamcrest`HC_assertThatWithLocation + 630
frame #8: 0x0000000100039eb7 ochamcrestTestTests`-[ochamcrestTestTests test](self=0x00000001021f4aa0, _cmd=0x00007fff89f576ea) + 71 at ochamcrestTestTests.m:11
frame #9: 0x00007fff8d47a09c CoreFoundation`__invoking___ + 140
frame #10: 0x00007fff8d479f37 CoreFoundation`-[NSInvocation invoke] + 263
frame #11: 0x0000000100040a05 SenTestingKit`-[SenTestCase invokeTest] + 164
frame #12: 0x0000000100040b7f SenTestingKit`-[SenTestCase performTest:] + 173
frame #13: 0x0000000100040453 SenTestingKit`-[SenTest run] + 65
frame #14: 0x0000000100043dc1 SenTestingKit`-[SenTestSuite performTest:] + 125
frame #15: 0x0000000100040453 SenTestingKit`-[SenTest run] + 65
frame #16: 0x0000000100043dc1 SenTestingKit`-[SenTestSuite performTest:] + 125
frame #17: 0x0000000100040453 SenTestingKit`-[SenTest run] + 65
frame #18: 0x0000000100043dc1 SenTestingKit`-[SenTestSuite performTest:] + 125
frame #19: 0x0000000100040453 SenTestingKit`-[SenTest run] + 65
frame #20: 0x0000000100042b18 SenTestingKit`+[SenTestProbe runTests:] + 134
frame #21: 0x00007fff89d57395 Foundation`__NSFireDelayedPerform + 358
frame #22: 0x00007fff8d443804 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
frame #23: 0x00007fff8d44331d CoreFoundation`__CFRunLoopDoTimer + 557
frame #24: 0x00007fff8d428ad9 CoreFoundation`__CFRunLoopRun + 1529
frame #25: 0x00007fff8d4280e2 CoreFoundation`CFRunLoopRunSpecific + 290
frame #26: 0x00007fff8f2cfeb4 HIToolbox`RunCurrentEventLoopInMode + 209
frame #27: 0x00007fff8f2cfb94 HIToolbox`ReceiveNextEventCommon + 166
frame #28: 0x00007fff8f2cfae3 HIToolbox`BlockUntilNextEventMatchingListInMode + 62
frame #29: 0x00007fff93708563 AppKit`_DPSNextEvent + 685
frame #30: 0x00007fff93707e22 AppKit`-[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
frame #31: 0x00007fff936ff1d3 AppKit`-[NSApplication run] + 517
frame #32: 0x00007fff936a3c06 AppKit`NSApplicationMain + 869
frame #33: 0x0000000100001522 ochamcrestTest`main(argc=8, argv=0x00007fff5fbff3d8) + 34 at main.m:13
frame #34: 0x00007fff8a1587e1 libdyld.dylib`start + 1`

Odd Issue with Infinite Recursion with HCBaseMatcher, HCBaseDescription, and HC_assertThatWithLocation

Hey there -

I've had OCHamcrest in various test suites for years without any issue. About a month ago I switched the installation mechanism from a direct source import into an installation via CocoaPods and my suite ran clean. Some time after that, when I ran into my first failing test case Xcode spun off into oblivion and eventually overflowed and terminated the program.

Looking at my failures, there is an infinite recursion problem that begins with HC_assertThatWithLocation and then invokes a recursive cycle of description methods. I have tried both Hamcrest 1.7 and 1.8 via Pods and I am really not sure how this cycle has come about nor if it is specific to the CocoaPods installation.

A dump of the beginning of the recursive cycle follows. Any ideas?


#160538 0x053f16d7 in -[HCBaseMatcher description] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseMatcher.m:21
#160539 0x053f0f99 in -[HCBaseDescription appendObjectDescriptionOf:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseDescription.m:40
#160540 0x053f0f4c in -[HCBaseDescription appendDescriptionOf:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseDescription.m:33
#160541 0x053f198c in +[HCStringDescription stringFrom:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCStringDescription.m:20
#160542 0x053f16d7 in -[HCBaseMatcher description] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseMatcher.m:21
#160543 0x053f0f99 in -[HCBaseDescription appendObjectDescriptionOf:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseDescription.m:40
#160544 0x053f0f4c in -[HCBaseDescription appendDescriptionOf:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseDescription.m:33
#160545 0x053f198c in +[HCStringDescription stringFrom:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCStringDescription.m:20
#160546 0x053f16d7 in -[HCBaseMatcher description] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseMatcher.m:21
#160547 0x053f0f99 in -[HCBaseDescription appendObjectDescriptionOf:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseDescription.m:40
#160548 0x053f0f4c in -[HCBaseDescription appendDescriptionOf:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseDescription.m:33
#160549 0x053f198c in +[HCStringDescription stringFrom:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCStringDescription.m:20
#160550 0x053f16d7 in -[HCBaseMatcher description] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseMatcher.m:21
#160551 0x053f0f99 in -[HCBaseDescription appendObjectDescriptionOf:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseDescription.m:40
#160552 0x053f0f4c in -[HCBaseDescription appendDescriptionOf:] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCBaseDescription.m:33
#160553 0x053f0a1f in HC_assertThatWithLocation at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Pods/OCHamcrest/Source/Core/HCAssertThat.m:86
#160554 0x052b0c04 in -[RKMIMETypeSerializationTest testSerializationOfObjectInvokesRegisteredSerializationClass] at /Users/blake/Projects/GateGuru/GateGuru-iOS.master/Libraries/RestKit/Tests/Logic/ObjectMapping/RKMIMETypeSerializationTest.m:192
``

Name clash with between HC_empty() std::string::empty()

When using #define HC_SHORTHAND in my test pch I get this linker error in my application:

"std::string::HC_empty() const", referenced from: xxx

I won't use hc shorthand for now. When the naming conflict is resolved I'll give it a try again.

Thanks!

Exception thrown for failing assertions on collections containing mockProtocol objects.

For example, the following test will thrown an exception as a result of an unrecognised selector (isNSString__) being invoked on NSProxy.

- (void)test_crashesXCTest {

    NSArray* arrayA = @[];
    NSArray* arrayB = @[mockProtocol(@protocol(NSCopying))];

    assertThat(arrayA, is(equalTo(arrayB)));
}

The issue seems to happen if either arrayA or arrayB contain a mocked protocol object and the assertion fails. So the following will also cause the same issue:

- (void)test_crashesXCTest1 {

    NSArray* arrayA = @[ [NSObject new] ];
    NSArray* arrayB = @[ mockProtocol(@protocol(NSCopying)) ];

    assertThat(arrayA, is(equalTo(arrayB)));
}

- (void)test_crashesXCTest2 {

    NSArray* arrayA = @[ mockProtocol(@protocol(NSCoding)) ];
    NSArray* arrayB = @[ mockProtocol(@protocol(NSCopying)) ];

    assertThat(arrayA, is(equalTo(arrayB)));
}

- (void)test_crashesXCTest3 {

    NSArray* arrayA = @[ mockProtocol(@protocol(NSCopying)) ];
    NSArray* arrayB = @[];

    assertThat(arrayA, is(equalTo(arrayB)));
}

And so on, you get the idea.
The error occurs in Apple code, but flow of control leaves the OCHamcrest framework from HCBaseDescription.m at line 33. Replacing the description invocation with debugDescription fixes the issue, however I'm not sure if that's actually the desired behaviour?

- (id <HCDescription>)appendObjectDescriptionOf:(id)value
{
    // NSString *description = [value description]; 
    NSString *description = [value debugDescription]; // (this is the fix)
    NSUInteger descriptionLength = description.length;
    if (descriptionLength == 0)
        [self append:[NSString stringWithFormat:@"<%@: %p>", NSStringFromClass([value class]), (__bridge void *)value]];
    else if ([description characterAtIndex:0] == '<'
             && [description characterAtIndex:descriptionLength - 1] == '>')
    {
        [self append:description];
    }
    else
    {
        [self append:@"<"];
        [self append:description];
        [self append:@">"];
    }
    return self;
}

Here is a sample stacktrace:

caught "NSInvalidArgumentException", "*** -[NSProxy doesNotRecognizeSelector:isNSString__] called!"
(
    0   CoreFoundation                      0x000000010dfb6d85 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010da2adeb objc_exception_throw + 48
    2   CoreFoundation                      0x000000010dfb6cbd +[NSException raise:format:] + 205
    3   CoreFoundation                      0x000000010df05cfa ___forwarding___ + 970
    4   CoreFoundation                      0x000000010df058a8 _CF_forwarding_prep_0 + 120
    5   CoreFoundation                      0x000000010dfa6d59 -[NSArray descriptionWithLocale:indent:] + 393
    6   FlytTests                           0x00000001183cc707 -[HCBaseDescription appendObjectDescriptionOf:] + 55
    7   FlytTests                           0x00000001183cc68c -[HCBaseDescription appendDescriptionOf:] + 300
    8   FlytTests                           0x00000001183d904c -[HCIsEqual describeTo:] + 348
    9   FlytTests                           0x00000001183cc5ef -[HCBaseDescription appendDescriptionOf:] + 143
    10  FlytTests                           0x00000001183d1981 -[HCIs describeTo:] + 97
    11  FlytTests                           0x00000001183cc5ef -[HCBaseDescription appendDescriptionOf:] + 143
    12  FlytTests                           0x00000001183cc439 HCDescribeMismatch + 169
    13  FlytTests                           0x00000001183cbdad reportMismatch + 237
    14  FlytTests                           0x00000001183cbc86 HC_assertThatWithLocation + 166
    15  FlytTests                           0x0000000118263dee -[FLYLocationsListUpdatesHelperTests test_crashesXCTest] + 302
    16  CoreFoundation                      0x000000010de9f5cc __invoking___ + 140
    17  CoreFoundation                      0x000000010de9f41e -[NSInvocation invoke] + 286
    18  XCTest                              0x000000010d4c3ef3 __24-[XCTestCase invokeTest]_block_invoke_2 + 362
    19  XCTest                              0x000000010d4f8613 -[XCTestContext performInScope:] + 190
    20  XCTest                              0x000000010d4c3d78 -[XCTestCase invokeTest] + 169
    21  XCTest                              0x000000010d4c43a2 -[XCTestCase performTest:] + 459
    22  XCTest                              0x000000010d4c1cf7 -[XCTestSuite performTest:] + 396
    23  XCTest                              0x000000010d4c1cf7 -[XCTestSuite performTest:] + 396
    24  XCTest                              0x000000010d4aeb10 __25-[XCTestDriver _runSuite]_block_invoke + 51
    25  XCTest                              0x000000010d4cfb4c -[XCTestObservationCenter _observeTestExecutionForBlock:] + 640
    26  XCTest                              0x000000010d4aea55 -[XCTestDriver _runSuite] + 453
    27  XCTest                              0x000000010d4af7d1 -[XCTestDriver _checkForTestManager] + 259
    28  XCTest                              0x000000010d4f9a9a _XCTestMain + 628
    29  xctest                              0x000000010d43520f xctest + 8719
    30  libdyld.dylib                       0x000000011089392d start + 1
    31  ???                                 0x0000000000000005 0x0 + 5

We are using the version of OCHamcrest that comes bundled with the latest release of OCMockito, which is v5.4.0 I think, (Incidentally, are you planning to update OCMockito to use the latest release of OCHamcrest (6.0.0) at any point?).

Many thanks.

Boolean matcher accepts values other than YES and NO, i.e. @NO

Hello Jon,

First of all thank you very much for a wonderful piece of software, and
your precious input in Objective-C software community especially in
terms of software quality.

An issue I have stumbled across is but a tiny glitch: When I have accidentally
prepended an expected boolean value with an @, I got this error message:

Expected a BOOL with value «YES», but was «YES»

Obviously, the framework has detected that the value does not match the
expectation, however the error message looks puzzling.
One of the ways of handling this, as I see it, is to raise an error in
-HCIsEqualToBool#initWithValue: if the passed value isn't either
YES or NO, instead of accepting any value.

Best regards,
/me

Use #defines for switching to unprefixed versions

Hello!

Future builds of OCHamcrest will end up being built as frameworks in CocoaPods, the downside of this for you is that #defines in the app itself don't affect the building of the framework now. This means the
#define HC_SHORTHAND cannot affect the syntax of a given framework. For specta/expecta - I've recommend switching to the opposite ref: specta/expecta#124

Strange error message for hasCountOfFailure

Steps to reproduce:

  1. Return an array with 5 elements.
  2. assert hasCountOf(2)

Excepted Outcome:

Failure with descriptive error message.

Actual Outcome:

Unknown.m:0: error: -[NSArray_MPRegionTests test_marshals_json_to_object_list] : -[__NSCFNumber message]: unrecognized selector sent to instance 0x9e094e0

Example test:

  • (void)test_marshals_json_to_object_list
    {
    NSData* jsonData = [[TyphoonBundleResource withName:@"getRegionListResponse.json"] data];

    NSError* e = nil;
    NSArray* json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
    NSArray* regions = [json asRegionList];
    LogDebug(@"Regions: %@", regions);
    assertThat(regions, hasCountOf(2));
    }

OCHamcrest 3.0.1 does not seem to work with the "Test Failure" breakpoint in XCode 5.1

I have recently started to program in Objective C and am a huge advocate of TDD. I usually program in Java and love the hamcrest framework so I was intrigued by this library and started to use it for my Objective C apps. I created a test that deliberately fails and added a "Test Failure" breakpoint. However I find that this breakpoint is not fired when the test fails. It seems to fail if I write a standard XCTest test using XCTest assertions. Here is my test code:

#import <XCTest/XCTest.h>
#define HC_SHORTHAND
#import <OCHamcrest/OCHamcrest.h>

@interface HamcrestTests : XCTestCase
@end

@implementation HamcrestTests
- (void)testExample
{
    assertThat(@(40+1), equalTo(@42));
//    XCTAssertEqual(@(40+1), @42, "values do not match");
}
@end

If I comment out the "assertThat..." line and uncomment the "XCTAssertEqual..." line then the test correctly breaks into the debugger on test failure.

Am I using OCHamcrest incorrectly or is this a known limitation?

Thanks in advance.

Some macros for async unit tests and possibly addition to OCMockObject

Hi

It could be really great to have my little project https://github.com/hfossli/AGWaitForAsyncTestHelper/ become a part of OCHamcrest. Just wanting to let you know.

I guess we could do awesome stuff like if we just added this method to OCMockObject

// returns true/false if all expectations is fullfilled (does not throw exception)
- (BOOL)expectationsFullfilled;

Then we could solve this guys problems http://stackoverflow.com/questions/12463733/objective-c-unit-testing-dispatch-async-block like this:

- (void)testShouldFetchUserDataUsingCorrectId
{
    OCMockObject *serviceMock = [OCMockObject niceMockForClass:[ServiceClient class]];
    [[serviceMock expect] fetchDataForUserId:userId];

    static NSString *userId = @"sdfsdfsdfsdf";
    self.viewController.userId = userId;
    self.viewController.serviceClient = serviceMock;
    [self.viewController view];

    /*
     Will wait wile expectations is not fullfilled. 
     Will throw error if expecatations is not met within 1.0 second.
     */
    WAIT_WHILE(![serviceMock expectationsFullfilled], (NSTimeInterval) 1.0);
    [serviceMock verify];
}

Let me know what you think! :)

Contribution for "assertThat(...., throwsExceptionOfType(...)) "?

I've just implemented a matcher for 'throwsExceptionOfType' in my project.

NSException *exception = [NSException exceptionWithName:@"" reason:@"" userInfo:nil];
assertThat(^(){ @throw exception;}, throwsExceptionOfType([DesignByContractException class]) );

Would you guys be interested to have it in a pull-request at all?

Version tag request: include HCConformsToProtocol method shadowing fix to fix conflict with GTM

The latest non-HEAD version of OCHamcrest available in Cocoapods (1.9) is broken when used with the GTM Unit Testing suite. The GTM test runner calls conformsToProtocol: on every class loaded by the runtime, interprets the non-nil matcher object returned by HCConformsToProtocol as a YES and crashes due to the unrecognized selector called on that class. This issue is fixed with a simple name change in 6592655. I'd love to be able to get this fix without having to use the bleeding edge version of the repo. Might I humbly suggest a v1.9.1?

Thanks!

XCTest test failure bug

Rather than a description of why the test failed, the error "failWithException: unrecognized selector sent to instance" is given when using XCTest. This bug was introduced in version 2.1.0.

OCHamcrest 1.8 and 1.7 running on devices - file universal but does not contain armv6 slice

hello,

i am not sure this is the best place to ask this question. if it is not, please point me to right place.

i came across this error while trying to run some tests on my devices:

<OCHamcrest> file is universal but does not contain a(n) armv6 slice for architecture armv6

i had a look at the OCHamcrestIOS binary and saw that armv6 was not included an included architecture.

OCHamcrest-1.8/OCHamcrestIOS.framework]: $ lipo -info OCHamcrestIOS 
Architectures in the fat file: OCHamcrestIOS are: armv7 i386 

i cloned the repository, added armv6 to the Architectures list for the libochamcrest target then ran MakeIOSFramework.sh

inspecting the resulting binary i now see armv6 included:

$ lipo -info OCHamcrestIOS
Architectures in the fat file: OCHamcrestIOS are: armv7 armv6 i386 

after adding the new framework to my test target, i found that i could run on my ipad, iphone 3G (4.2.1), and iphone 4S.

is there some reason why armv6 is not in the architectures list?

i am really loving this framework! thanks!

jjm

Error when using OCHamcrest and OCMockito together with CocoaPods

When using OCHamcrest and OCMockito an error occurs:

target :MyAppTests do
  pod 'OCHamcrest'
  pod 'OCMockito'
  pod 'Expecta'
end

What should happen is that OCMockito's transitive dependency on OCHamcrest should win in terms of version number. What actually happens is that the latest OCHamcrest is pulled down. This version is not compatible with the current version of OCMockito.

I'm not sure if this is a limitation in CocoaPods or an error in the spec file.

OCHamcrest Matcher for NSError **

Hi,

I was wondering if there exists a OCHamcrest Matcher for NSError ** method parameters?

I'm aware I can use statements like:

" [[given([self.mockManager addItemWithName:testName error:&error]) withMatcher:anything() forArgument:1] willReturnBool:YES];"

but how do I verify with "anything"?

Thanks,

Ronak Patel

5.4.0 Release introduced GCC warning

This warning appeared after 5.4.0 release

HCIsEqualCompressingWhiteSpace.h:43:85: GCC does not allow 'deprecated' attribute in this position on a function definition

Add Swift example projects

I am just starting out with Xcode 6 and Swift, and have been unable to get the OCHamcrestIOS framework working on my first project, even when following instructions I found on StackOverflow. It would really help to have a minimal working example...

Remove extra semicolon in HCGenericTestFailureReporter.m

Building OCHamcrest with -Wsemicolon-before-method-body cause the following warning to be emitted by clang:

HCGenericTestFailureReporter.m:16:58: error: semicolon before method body is ignored [-Werror,-Wsemicolon-before-method-body]

  • (void)executeHandlingOfFailure:(HCTestFailure *)failure;
    ^

This should be as simple as removing the extra semicolon.

Verify doesn't like instanceOf([NSDictionary class])

Hi,
with the following unit test I'm using Mockito to mock NSUserDefaults but when I try to verify using OCHamcrest matcher to test that the param is an instance of an NSDictionary I get the warning:

Sending 'id{HCMatcher}' to parameter of incompatible type 'NSDictionary *'

NSUserDefaults *userDefaultsMock = mockClass([NSUserDefaults class]); 

Engineer *sut = [[Engineer alloc]init];

[given([userDefaultsMock stringForKey:@"engineerId"]) willReturn:@"02345"];

BOOL result = [sut setCurrentEngineerId:@"02345" userDefaults:userDefaultsMock];
[verify(userDefaultsMock) registerDefaults:instanceOf([NSDictionary class])];

contains matcher

Seems like the contains matcher is not working correctly. This fails...

NSArray *a = [NSArray arrayWithObjects:@"a",@"b",@"c",nil];
assertThat(a, contains(@"a",@"b",@"c"));

Error message:

Expected a collection containing ["a", "b", "c", "b", "c"], but no item matched: "b"

I'm testing again v1.4. Similarly, containsInAnyOrder also fails, but hasItems works correctly.

Error that OCHamcrest.h is an incomplete umbrella header

Cartfile contains github "hamcrest/OCHamcrest" "v5.1.0"

This is the first time I've compiled OCHamcrest with carthage. I get the following error when using the framework.

<module-includes>:1:1: error: umbrella header for module 'OCHamcrest' does not include header 'HCBaseDescription.h' [-Werror,-Wincomplete-umbrella]
#import "/Users/brennan/project/Carthage/Build/iOS/OCHamcrest.framework/Headers/OCHamcrest.h"
^
<module-includes>:1:1: error: umbrella header for module 'OCHamcrest' does not include header 'HCCollect.h' [-Werror,-Wincomplete-umbrella]
<module-includes>:1:1: error: umbrella header for module 'OCHamcrest' does not include header 'HCRequireNonNilObject.h' [-Werror,-Wincomplete-umbrella]
<module-includes>:1:1: error: umbrella header for module 'OCHamcrest' does not include header 'HCStringDescription.h' [-Werror,-Wincomplete-umbrella]
<module-includes>:1:1: error: umbrella header for module 'OCHamcrest' does not include header 'HCWrapInMatcher.h' [-Werror,-Wincomplete-umbrella]
5 errors generated.
/Users/brennan/project/Tests/UnitTests/Resources/UnitTests-Prefix.pch:15:13: fatal error: could not build module 'OCHamcrest'
    #import <OCHamcrest/OCHamcrest.h>
     ~~~~~~~^

conflict between HC_conformsToProtocol and NSObject conformsToProtocol: in 1.7

hey,

thanks for your work on OCHamcrest; less typing - i love it.

i am not sure if this is bug or not, but i thought i would let you know about it.

i have a test target that depends on my iOS application target. in one of my application classes i use the NSObject conformsToProtocol: method to check if a view conforms to a protocol.

i linked the OCHamcrest 1.7 framework to my test target and now i see the following compiler error in my test target:

"No visible @interface for 'UIView' declares the selector 'HC_conformsToProtocol:'"

this is the offending line in my application:

[view conformsToProtocol:@protocol(V8HorizontalPickerElementView)]

i can resolve the compiler error by doing any of the following:

  • removing my application target as a dependency of my test target,
  • using OCHamcrest 1.6, or
  • removing #define HC_SHORTHAND from my test target .pch

am i not supposed to put the #define HC_SHORTHAND in the prefix header?

thanks!

jjm

Expected nil, but was nil

How does this even happen?

Here is code to reproduce:

       _scriptManager = OCMPartialMock([ScriptsManager manager]);
   
       OCMStub([_scriptManager cachedData]).andReturn(nilValue());
       id expected = nilValue();
       id actual = [_scriptManager cachedData];
       assertThat(actual, equalTo(expected));

code from the library:

- (BOOL)matches:(id)item
{
    if (item == nil)
        return self.expectedValue == nil;
    return [item isEqual:self.expectedValue];
}

item == nil returns false

please see stackoverflow post below.

http://stackoverflow.com/a/5914886/2136812

improve error message for hasProperty()

Given this HC_SHORTHAND test:

- (void)testFooPropertyIsBar
{
  assertThat(_sut, hasProperty(@"foo", @"bar"));
}

and a _sut with property foo having the value “baz” will fail with this message:

/path/to/project/Tests/XXXSomethingTest.m:<LINE>: error: -[XXXSomethingTest testFooPropertyIsBar] : Expected an object with foo "bar", but was <XXXSomething: 0x618000033aa0>

I think it would help development/testing if the message would look more like this:

/path/to/project/Tests/XXXSomethingTest.m:<LINE>: error: -[XXXSomethingTest testFooPropertyIsBar] : Expected an object with foo "bar", but was <XXXSomething: 0x618000033aa0> with foo "baz"

(Hint: The difference is at the end of these lines.)

assertWithTimeout and thatEventually functions are not available in OCHamcrest-4.0.1

I downloaded OCHamcrest-4.0.1 framework, copied to my project and added the following:

define HC_SHORTHAND

import <OCHamcrestIOS/OCHamcrestIOS.h>

When trying to compile my tests I got the following errors from XCode7:
Implicit declaration of function 'assertWithTimeout' is invalid in C99
Implicit declaration of function 'thatEventually' is invalid in C99

Failed to build with MakeDistribution.sh

Here is log:

MacBook-Pro-Pavel-2:Source pavellitvinenko$ ./MakeDistribution.sh
Preparing clean build
Building OCHamcrest - Release
=== BUILD NATIVE TARGET OCHamcrest OF PROJECT OCHamcrest WITH CONFIGURATION Release ===
Check dependencies
OS X deployment target '10.9' for architecture 'i386' and variant 'normal' is greater than the maximum value '10.8' for the OS X 10.8 SDK.

SymLink build/Release/OCHamcrest.framework/Versions/Current A
cd "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source"
/bin/ln -sf A "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/Release/OCHamcrest.framework/Versions/Current"

SymLink build/Release/OCHamcrest.framework/OCHamcrest Versions/Current/OCHamcrest
cd "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source"
/bin/ln -sf Versions/Current/OCHamcrest "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/Release/OCHamcrest.framework/OCHamcrest"

SymLink build/Release/OCHamcrest.framework/Resources Versions/Current/Resources
cd "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source"
/bin/ln -sf Versions/Current/Resources "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/Release/OCHamcrest.framework/Resources"

SymLink build/Release/OCHamcrest.framework/Headers Versions/Current/Headers
cd "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source"
/bin/ln -sf Versions/Current/Headers "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/Release/OCHamcrest.framework/Headers"

ProcessInfoPlistFile build/Release/OCHamcrest.framework/Versions/A/Resources/Info.plist OCHamcrest-Info.plist
cd "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source"
builtin-infoPlistUtility OCHamcrest-Info.plist -expandbuildsettings -platform macosx -o "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/Release/OCHamcrest.framework/Versions/A/Resources/Info.plist"

ProcessPCH /var/folders/9g/12qxsh156sv5jhm2qlzks_n80000gn/C/com.apple.Xcode.501/SharedPrecompiledHeaders/OCHamcrest-Prefix-elfaevfmxmbqqsfiubtrnagmzcjn/OCHamcrest-Prefix.pch.pth OCHamcrest-Prefix.pch normal i386 objective-c com.apple.compilers.llvm.clang.1_0.compiler
cd "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source"
setenv LANG en_US.US-ASCII
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c-header -arch i386 -fmessage-length=0 -std=gnu99 -fobjc-arc -Wno-trigraphs -fpascal-strings -O3 -Wno-missing-field-initializers -Wno-missing-prototypes -Wno-return-type -Wno-implicit-atomic-properties -Wno-receiver-is-weak -Wformat -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wno-unused-variable -Wunused-value -Wno-empty-body -Wno-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wno-constant-conversion -Wno-int-conversion -Wno-enum-conversion -Wno-shorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wno-undeclared-selector -Wno-deprecated-implementations -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk -fasm-blocks -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -mmacosx-version-min=10.9 -g -Wno-sign-conversion -iquote "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/OCHamcrest.build/Release/OCHamcrest.build/OCHamcrest-generated-files.hmap" "-I/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/OCHamcrest.build/Release/OCHamcrest.build/OCHamcrest-own-target-headers.hmap" "-I/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/OCHamcrest.build/Release/OCHamcrest.build/OCHamcrest-all-target-headers.hmap" -iquote "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/OCHamcrest.build/Release/OCHamcrest.build/OCHamcrest-project-headers.hmap" "-I/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/Release/include" -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include "-I/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/OCHamcrest.build/Release/OCHamcrest.build/DerivedSources/i386" "-I/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/OCHamcrest.build/Release/OCHamcrest.build/DerivedSources" "-F/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/build/Release" -F/Applications/Xcode.app/Contents/Developer/Library/Frameworks -fobjc-arc-exceptions --serialize-diagnostics /var/folders/9g/12qxsh156sv5jhm2qlzks_n80000gn/C/com.apple.Xcode.501/SharedPrecompiledHeaders/OCHamcrest-Prefix-elfaevfmxmbqqsfiubtrnagmzcjn/OCHamcrest-Prefix.pch.dia -c "/Users/pavellitvinenko/Documents/My Projects/LoopsequeDJ/Tests/Libraries/OCHamcrest/Source/OCHamcrest-Prefix.pch" -o /var/folders/9g/12qxsh156sv5jhm2qlzks_n80000gn/C/com.apple.Xcode.501/SharedPrecompiledHeaders/OCHamcrest-Prefix-elfaevfmxmbqqsfiubtrnagmzcjn/OCHamcrest-Prefix.pch.pth -MMD -MT dependencies -MF /var/folders/9g/12qxsh156sv5jhm2qlzks_n80000gn/C/com.apple.Xcode.501/SharedPrecompiledHeaders/OCHamcrest-Prefix-elfaevfmxmbqqsfiubtrnagmzcjn/OCHamcrest-Prefix.pch.d
error: -fobjc-arc is not supported on platforms using the legacy runtime
2013-08-21 18:44:45.387 xcodebuild[4857:2507] DVTAssertions: Warning in /SourceCache/IDEXcode3ProjectSupport/IDEXcode3ProjectSupport-2110/Xcode3Sources/XcodeIDE/Frameworks/DevToolsBase/pbxcore/Target.subproj/BuildCommandResultsPostprocessing/XCClangResultsPostprocessor.m:98
Details: Unable to read diagnostics from file "/var/folders/9g/12qxsh156sv5jhm2qlzks_n80000gn/C/com.apple.Xcode.501/SharedPrecompiledHeaders/OCHamcrest-Prefix-elfaevfmxmbqqsfiubtrnagmzcjn/OCHamcrest-Prefix.pch.dia" (Invalid File): Bad header in diagnostics file
Object: <XCClangResultsPostprocessor: 0x4018ac400>
Method: -postprocessResultsForCommandInvocation:
Thread: <NSThread: 0x4018ac3a0>{name = (null), num = 4}
Please file a bug at http://bugreport.apple.com with this warning message and any useful information you can provide.
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

** BUILD FAILED **

The following build commands failed:
ProcessPCH /var/folders/9g/12qxsh156sv5jhm2qlzks_n80000gn/C/com.apple.Xcode.501/SharedPrecompiledHeaders/OCHamcrest-Prefix-elfaevfmxmbqqsfiubtrnagmzcjn/OCHamcrest-Prefix.pch.pth OCHamcrest-Prefix.pch normal i386 objective-c com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)
OCHamcrest release build failed
MacBook-Pro-Pavel-2:Source pavellitvinenko$

Removing the "IOS" suffix from the iOS pre-build framework.

OCHamcrest adds an “iOS” suffix for the iOS built framework. This now means that you need to import OCHamcrestIOS/OCHamcrestIOS.h to your code. However, when you change your project to use CocoaPods instead, you now find yourself having to import OCHamcrest/OCHamcrest.h since there is no “iOS” suffix there. This seems to cause problems when moving from the framework to CocoaPods, especially for large projects.

One way to handle this issue is by building OCHamcrest as a static library and then flattening the source which seems quite tedious, especially when the “IOS” suffix doesn’t seem to serve any other purpose than to distinguish it from the MacOSX Framework. Maybe we could add the frameworks in separate .zip files and not alter the code itself?

Incompresible error message on OCMock 2.0

When I do some assertion with NSUInteger and the test fails I get some generic hard-to-understand errors:

assertThatInteger(3, is(equalToInteger(1)));

or

assertThatUnsignedInteger(3, is(equalToUnsignedInteger(1)));

Give me this error:

Test rig '/Applications/Xcode.app/Contents/Developer/Tool/otest' exited abnormally with code 139 (it may have crashed)

instead using OCMock 1.9 I receive a nice error:

Expected <1>, but was <3>

HCSelfDescribing.h should include HCDescription.h

When creating a new matcher subclass of HCBaseMatcher, HCBaseMatcher.h and HCDescription.h must be imported to describe to the object. Changing the @protocol forward declaration in HCBaseMatcher.h to an import would remove the need to include HCDescription.h too.

Any reason I'm missing to prefer the protocol forward declaration over importing the protocol defining header?

Warning in HCIsInstanceOf

Class HCIsInstanceOf has started to generate warning:

Incompatible pointer types sending 'Class' to parameter of type 'NSString *'

for method:

+ (instancetype)isInstanceOf:(Class)type
{
    return [[self alloc] initWithType:type];
}

I'm using XCode 6.3.1

Is assertThat supposed to generate errors that are clickable and jump to the line of code where the assert failed?

Hello,

The documentation says that when an assert fails, that one can click the error in Xcode and Xcode will take the user to the line of code with the error. I'm running Xcode 4.4, and that does not happen.

Xcode doesn't appear to know where the error occurred and I must manually go find the correct file and line. Is this correct behavior?

If I use the STAssert macros, Xcode can figure out where the error occurred and jump to the line of code, when the error is clicked.

Asserting a boolean documentation

Maybe the answer of my question could be added to the Readme.

How to check this :

  XCTAssertFalse(isLast);

Using OCHamcrest like this :

 assertThatBool(isLast, isFalse());

is not possible since isFalse does not exists, so we should use :

 assertThatBool(isLast, equalToBool(NO));

Maybe, adding isFalse() and isTrue() could improve readability over boolean assertions.

OCMockito-Prefix.pch.pch: No object file for requested architecture

The iOS Framework included in the ZIP at the https://github.com/hamcrest/OCHamcrest/releases/tag/v4.3.0 seems to include from non-existing file

while processing ..../Dependencies/OCHamcrest/OCHamcrestIOS.framework/OCHamcrestIOS(HCBaseDescription.o): warning: /var/folders/84/3k6gp4_n5js57qwpk272mrhr0000gp/C/com.apple.DeveloperTools/7.0.1-7A1001/Xcode/SharedPrecompiledHeaders/OCHamcrest-Prefix-bjsliglvsggvvfdmgxqfxofiwpmx/OCHamcrest-Prefix.pch.pch: No such file or directory

isNot(isEmpty())

.. probably too late to change, but this would read a little nicer if it was: isNot(empty())

Capturing NSStackBlock leads to EXC_BAD_ACCESS

- (void)capture:(id)item
{
if (self.captureEnabled)
{
id value = item ?: [NSNull null];
[self.values addObject:value];
}
}

Let's say we want to test code like this:

- (void)foo {
  __weak typeof(self) weakSelf = self;
  [_asyncWorker doWorkWithCompletion:^(){
    [weakSelf _onCompletion];
  }];
}

The completion block will be of type NSStackBlock since it is never assigned to a variable. If we try to test this code using a mocked asyncWorker like this:

MKTArgumentCaptor *captor = [MKTArgumentCaptor new];
[verify(mockedWorker) doWorkWithCompletion:captor.capture];

[objectUnderTest foo];

dispatch_block_t completion = captor.value;
completion();

we run into a EXC_BAD_ACCESS, because the foo's stack has gone out of scope before completion is called and therefore we are accessing the block after it's been released.

NSStackBlocks get copied on the heap lazily (upon first copy). Usually ARC inserts block copy statements automagically across method boundaries. However, it doesn't do so if the method signature specifies a non-block type (which - (void)capture:(id)item does).

If, on the other hand, you pass a block pointer as an argument to a function parameter whose declared compile-time type is a non-block object pointer type, then that function wouldn't be taking responsibility for any block copying, because for all it knows it's just a regular object, that just needs to be retained if stored in a place that outlives the current scope. In this case, if you think that the function may possibly store the value beyond the end of the call, you should copy the block before passing it, and pass the copy instead. (https://stackoverflow.com/questions/35822645/understand-one-edge-case-of-block-memory-management-in-objc)

Currently, my workaround is to either in the production code assign the block to a local variable, explicitly call copy before passing, or use NSInvocation in the test code to get the argument from the invocation and manually copy it. Both solutions are not ideal.
Can we add a check for NSStackBlocks in capture: and call copy if we are dealing with a NSStackBlock? Or is there another solution?

instanceOf fails with custom class

Hi Jon,
thanks for the great framework. I am new to TDD and I really appreciate all the work and experience you've shared.

The following test fails and I am not sure if this is a bug or if I profoundly misunderstood some concept.

storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
MyViewController *sut = [storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
[sut view];
NSLog(@" data source is member of class: %@", [sut.dataSource class]);
assertThat(sut, hasProperty(@"dataSource", instanceOf([MyDataSourceClass class])));

The NSLog output is "data source is member of class: MyDataSourceClass"

When I declare the dataSource property as an NSArray instead of MyDataSourceClass the test works fine.

When I "p HC_assertThat(sut, HC_hasProperty(@"dataSource", HC_instanceOf([MyDataSourceClass class])));" in the debug console I get:

error: no matching function for call to 'HC_hasProperty'
note: candidate function not viable: no known conversion from 'objc_object *' to 'id' for 2nd argument

Support Cedar

Do this before #62 because jonreid/OCMockito#11 workaround relies on #undef given

  • Add assertThat and assertThatAfter variants that can be used in plain C functions (no self). Maybe assertThatC? Should still work with existing failure handler chain by falling down to generic handler.
  • Add way to register new failure handler at the top of the chain.
  • Provide HCTestFailureHandler for Cedar which ignores testCase and instead calls
    • [[CDRSpecFailure specFailureWithReason:reason fileName:x.fileName lineNumber:x.lineNumber] raise];

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.