2015-10-20 72 views
0

我對以下幾點很好奇。由於我有在類擴展中聲明的各種方法,是否可以使用XCTest對它們進行單元測試?課堂擴展中聲明的單元測試方法

例如,給定包含方法foo一類擴展:

@interface FooClass() 

-(NSString*)foo; 

@end 

如何測試FOO:在一個測試類?

非常感謝您的幫助!

回答

2

您不需要測試內部方法,因爲您可能在流程實施中更頻繁地進行更改。測試需要來自* .h文件,但如果您需要,您可以創建測試類別。你也可以使用運行時(例如 - performSelector)

RSFooClass.h

#import <Foundation/Foundation.h> 


@interface RSFooClass : NSObject 
@end 

RSFooClass.m

#import "RSFooClass.h" 


@implementation RSFooClass 

- (NSString *)foo { 
    return @"Hello world"; 
} 

- (NSInteger)sum:(NSInteger)a with:(NSInteger)b { 
    return a + b; 
} 

@end 

RSFooClassTest.m

#import <XCTest/XCTest.h> 
#import "RSFooClass.h" 


@interface RSFooClass (Testing) 

- (NSString *)foo; 
- (NSInteger)sum:(NSInteger)a with:(NSInteger)b; 

@end 


@interface RSFooClassTest : XCTestCase 

@property (strong, nonatomic) RSFooClass *foo; 

@end 


@implementation RSFooClassTest 

- (void)setUp { 
    [super setUp]; 
    // Put setup code here. This method is called before the invocation of each test method in the class. 

    self.foo = [[RSFooClass alloc] init]; 
} 

- (void)testFoo { 
    NSString *result = [self.foo foo]; 
    XCTAssertEqualObjects(result, @"Hello world"); 
} 

- (void)testSumWith { 
    NSInteger a = 1; 
    NSInteger b = 3; 
    NSInteger result = [self.foo sum:a with:b]; 
    NSInteger expected = a + b; 
    XCTAssertEqual(result, expected); 
} 

@end