Lena Bru
Lena Bru

Reputation: 13947

How to verify method was called

I want to test a certain method was called in response to an NSNotification being received

i've tried this:

_sut = mock([EAMainScreenViewController class]);
[_sut view];
[[NSNotificationCenter defaultCenter]postNotificationName:kNotificationPushReceived object:[UIApplication sharedApplication].delegate userInfo:nil];
[verify(_sut) pushReceived:anything()];

And my _sut viewDidLoad looks like this

- (void)viewDidLoad {
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushReceived:) name:kNotificationPushReceived object:[UIApplication sharedApplication].delegate];
}

why does my test fail expecting 1 invocation, and receiving 0 invocations ?

btw, if i debug - the debugger does stop at the method

Upvotes: 1

Views: 129

Answers (1)

Eugen Martynov
Eugen Martynov

Reputation: 20140

You should re-write your test to next:

- (void)setUp {
    _sut = [[EAMainScreenViewController alloc] <properInit>];
}

- (void)tearDown {
    //just in case
    [[NSNotificationCenter defaultCenter] removeObserver:_sut];
}

- (void)testThatNotificationPushReceived {
    [_sut viewDidLoad];

    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationPushReceived object:<probably some mock> userInfo:nil];

    //test something that happens with your mock
}

Upvotes: 0

Related Questions