简体   繁体   中英

Verify method call with OCMockito

I have these two methods in a ClassA

-(IBAction)onSubmit;
-(void)validateName:(NSString*)name;

@Implementation

- (IBAction)onSubmit {
    [self validateName:self.textfield.text];
}

-(void)validateName:(NSString*)name{
    // do something
}

My test look like the below:

//given
ClassA *classA = mock([ClassA class]);
classA.textfield.text = @"Foo";

// when 
[classA onSubmit];

[verify(classA) validateName:@"Foo"];

But that doesn't work, I keep getting:

Expected 1 matching invocation, but received 0

How can I write a test that verifies that validateName is executed, when onSubmit is being called.

Proper unit tests test internal state and external behavior. Your unit tests are testing whether your code does something, not how it does something. The state verification tells you that your intended results are achieved, while the behavior verification tells you that your collaborating objects correctly interface with your system under test. This allows you to do wonderful things like refactor.

A test of internal state goes like this:

Given an initial state , if the system under test does something , then the resultant state should be this .

A test of external behavior goes like this:

If the system under test does something , then another unit should do something else .

The first sort of tests are accomplished with standard assertions ( assertThat() calls in the case of OCHamcrest). The second sort of tests are (properly) accomplished with verification of test doubles ( verify() calls in the case of OCMockito).

It wouldn't make any sense to mock the system under test. If you find it necessary to test the internal behavior (ie the particular methods called by the system under test), then you need to map those behaviors to states. In your case this would mean that ClassA implements a flag such as BOOL nameValidated (preferably with the getter isNameValidated ) or a variable such as NSString *validatedName .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM