I have method which expects user's input
@implementation TeamFormation
- (void)run {
NSFileHandle *kbd = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [kbd availableData];
NSString *option = [[[NSString alloc] initWithData:inputData
encoding:NSUTF8StringEncoding] substringToIndex:1];
NSLog(@"%@",option);
}
@end
Then I would like to cover this method by a test case
@interface TeamFormationTests : XCTestCase
@end
@implementation TeamFormationTests
- (void)testTeamFormation {
TeamFormation *teamFormation = [TeamFormation new];
[teamFormation run];
// emulate user's input here
}
@end
So, how to emulate user's input in test case function?
You have many options how to achieve this. Two obvious below.
Change
runto accept an argument- (void)runto- (void)runWithFileHandle:(NSFileHandle *)handleMock it with protocol
Create
DataProviderprotocol:Make
NSFileHandleto conform to this protocol:Store an object implementing this protocol on
TeamFormation:By default, use stdin file handle:
Create
TestDataProviderin your test:And use it in
TestFormationTests: