kiwi-bdd / Kiwi

Simple BDD for iOS
BSD 3-Clause "New" or "Revised" License
4.14k stars 512 forks source link

NSInvalidArgumentException "Attempt to add non-NSObserver object <> as an observer of <KWMock>" raised #660

Closed andrey-sikerin closed 8 years ago

andrey-sikerin commented 8 years ago

Hi everyone,

I use Observer pattern and want to test it. Please look some piece of code:

@protocol InputEventsObserver<NSObject>

@optional

- (void)someEvent;

@end

@protocol InputEventsObservable<NSObject>

- (void)addObserver:(id<InputEventsObserver>)observer;
- (void)removeObserver:(id<InputEventsObserver>)observer;

@end

@interface Object
 - (id)initWithObservable:(id<InputEventsObservable>)observable;

- (void)prepareToPresentation;

@end

And I have following test:

    it(@"adds observer before presentation", ^{
       observable = [KWMock nullMockForProtocol:
        @protocol(InputEventsObservable)];
    [[observable should] receive:@selector(addObserver:)
                            withArguments:any()];

     object = [[Object alloc] initWithObservable:observable];  

      [object prepareForPresentation];
    });

My tests fails due to - NSInvalidArgumentException "Attempt to add non-NSObserver object <> as an observer of <KWMock>" raised.

It happens when [observable addObserver:] was called inside Object class.

If following line

 [[observable should] receive:@selector(addObserver:)
                            withArguments:any()];

is commented, code doesn't raise NSInvalidArgumentException.

If addObserver: is changed on some other name (addListener: for example) everything is good.

What is wrong with my code?

modocache commented 8 years ago

Thanks for the report, @andrey-sikerin! Hmm... that's a strange error message. I have a feeling it might have something to do with the private Apple NSObserver class, and with Kiwi's very powerful mocking capabilities. We might be mocking something unexpected.

For now, if addListener: works, I'd recommend just using that. 😅

Sorry for the trouble!