简体   繁体   中英

iOS Testing Mock Subclass With Properties Using Kiwi

I have an application, for which I use Objective Resource to create local objects to reflect remote responses.

The specific model classes have subclass an abstract-ish class to give them all a variety of additional functionality, most importantly the ability to serialize, write to disk, and load from disk, regardless regardless of what the specific properties are of that specific model object.

superclass.m

-(BOOL)saveToDisk{  
    ...serializes and encodes all properties to disk  
    ...return success
}


subclass.h : superclass

@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSArray* friends;
 ...etc

Then I would call

     instanceOfSubclass.name = "joe"  
     NSLog(@"save status = %d",[instanceOfSubclass saveToDisk]);

I am new to BDD and test driven development generally. How do I create a mock object, using kiwi, to test this functionality abstractly, since I use this framework in lots of projects.

Specifically, I want to build tests that ensure that a subclass with various types of properties can be saved loaded, deleted, and overwritten.

My understanding is that this is where stubs and mocks come in, but I can't seem to figure out how to mock properties. Do I have to create an actual class with those properties?

Properties are methods behind the scenes, so:

I managed to do this with a combination of the +mock method as mentioned by @aopsfan , then using -stub:andReturn: were I guessed at the name of the methods that implemented the properties. This example worked, impersonating a TCConnection (from the Twilio iOS SDK ):

// Instantiates a mocked object:
id fake_connection = [TCConnection mock];
// Creates a faked property accessor:
[fake_connection stub:@selector(parameters)
            andReturn:@{@"From": @"fake-caller"}];

// I could now call my TCDeviceDelegate 's
// -device:didReceiveIncomingConnection:
[myActualObject device:myActualObject.device
            didReceiveIncomingConnection:fake_connection];
// Check some results on the object:
[[myActualObject.connection should] equal:fake_connection];

This pattern particular example can probably be generalised to other situations. It's useful to call -stub (without the andReturn: ) parameter to silence methods that can't be called in a simulated fixture.

There is some documentation for you at this location . Basically, Kiwi provides an Objective-C category on NSObject that you have access to when you #import "Kiwi.h" . This allows all objects that inherit from NSObject to respond to +mock , mockWithName: , etc., which is configurable via the KWMock class.

Hope this helps, and sorry its a bit late :)

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