Reputation: 5177
I have something like
- (void)getData:(SomeParameter*)param
{
// Remotely call out for data returned asynchronously
// returns data via a delegate method
}
- (void)handleDataDelegateMethod:(NSData*)data
{
// Handle returned data
}
I want to write a unit test for this, how can I do something better than
NSData* returnedData = nil;
- (void)handleDataDelegateMethod:(NSData*)data
{
returnedData = data;
}
- (void)test
{
[obj getData:param];
while (!returnedData)
{
[NSThread sleep:1];
}
// Make tests on returnedData
}
Upvotes: 1
Views: 330
Reputation: 2035
If can't send mock data back to your delegate as Chuck says you could do the following:
Make your test a delegate so that it receives the callback.
Add fields to your test class callBackInvoked and errorHasOccurred. Set them both to NO.
Make the call to getData
Go around the main runloop, as follows:
NSDate *twoSecondsFromNow = [NSDate dateWithTimeIntervalSinceNow:2.0];
while (!callBackInvoked && !errorHasOccured && runCount-- && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:twoSecondsFromNow]) {
twoSecondsFromNow = [NSDate dateWithTimeIntervalSinceNow:2.0];
}
(You can set runCount to the number of times you think it would be reasonable to wait).
In your handleDataDelegateMethod in the test class set callBackInvoked to YES. Similarly, if you have an error callback you can set errorHasOccured to YES.
Your test should then assert that callBackInvoked is YES and erroHasOccurred is NO.
Upvotes: 1
Reputation: 237010
Have your object call out to a mock from the getData:
method and check that it calls out correctly.
Call the handleDelegateMethod:
method from another test with some ready-baked data and make sure it does whatever it's supposed to do with the data given.
Upvotes: 1