Unit testing private methods from a category?

后端 未结 2 1073
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 04:13

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 difficul

2条回答
  •  情深已故
    2020-12-16 04:38

    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 
    #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.

提交回复
热议问题