Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

ios - Unit testing private methods from a category?

I have a category on NSString class that contains a private helper method. It would be handy if I could use this method in my unit test. However I have difficulties to expose it. When I create a class extension on NSString and declare the method here, the method is not visible in unit test. And it doesn't matter if I create the class extension in a separate header file, or as a part of unit test .m file.

It looks like I am missing something here.

Any help guys?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Common unit testing guidance would tell you not to try and test your private methods. Only test via your public interfaces. Private methods are simply an implementation detail that could change at any time, when you refactor. Your public interfaces should be pretty stable, and will exercise your private methods.

However, if you still want to test your private category methods, the following works for me...

First, your category:

UIImage+Example.h

@interface UIImage (Example)    
@end

UIImage+Example.m

@implementation UIImage (Example)

+ (NSString *)examplePrivateMethod
{
    return @"Testing";
}

@end

MyExampleTests.m

#import <XCTest/XCTest.h>
#import "UIImage+Example.h"

@interface UIImage (Example_Test)
+ (NSString *)examplePrivateMethod;
@end

@interface MyExampleTests : XCTestCase
@end

@implementation MyExampleTests

- (void)testExample
{
    XCTAssertEqualObjects(@"Test", [UIImage examplePrivateMethod], @"Test should be test");
}

@end

Essentially, redeclare your private method in a new category in your test. However, as mentioned above this is exposing private methods just for the purpose of testing, and coupling your tests to your implementation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...