Randy
Randy

Reputation: 4525

How to test if a specific method is called

Hi there,

I am writing unit tests for my app and I am wondering if I can test if a specific method is called.

For instance, let's say I want to test that when the following dismiss method is called, the reallyDismiss method is also called :

- (void)dismiss
{
   [self reallyDismiss];
}

Is there something like :

- (void)testReallyDismissIsCalledWhenDismissIsCalled
{
    [self.viewController dismiss];
    XCTAssertMethodHasBeenCalled(@"reallyDismiss");
}

?

Upvotes: 2

Views: 2179

Answers (2)

Wain
Wain

Reputation: 119031

Not directly, no. You would usually use a mocking library to inject your own version of that method so that you can add an expectation that it's called or subclass the target class so that the subclass can intercept (and forward if required) the method call you're checking for.

Upvotes: 1

Pradeep K
Pradeep K

Reputation: 3661

You can refactor your code as

-(BOOL)dismiss {
   if someCondition {
        [self reallyDismiss];
        return YES;
   } else {
        return NO;
   }
}

- (void)testReallyDismissIsCalledWhenDismissIsCalled
{
    XCTAssertTrue([self.viewController dismiss], @"reallyDismiss");
}

Upvotes: 0

Related Questions