NSURL to file path in test bundle with XCTest

后端 未结 8 1580
栀梦
栀梦 2020-12-23 18:35

I am trying to write an iOS app using TDD and the new XCTest framework. One of my methods retrieves a file from the internet (given a NSURL object) and stores it in the user

8条回答
  •  -上瘾入骨i
    2020-12-23 19:20

    The problem I was facing was that application code was trying to access the main bundle for things like bundleIdentifier and since the main bundle wasn't my unit test project it would return nil.

    A hack around this that works in both Swift 3.0.1 and Objective-C is to create an Objective-C category on NSBundle and include it in your unit test project. You don't need a bridging header or anything. This category will get loaded and now when you application code asks for the main bundle your category will return the unit test bundle.

    @interface NSBundle (MainBundle)
    
    +(NSBundle *)mainBundle;
    
    @end
    
    @implementation NSBundle (Main)
    
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
    +(NSBundle *)mainBundle
    {
        return [NSBundle bundleForClass:[SomeUnitTest class]];
    }
    #pragma clang diagnostic pop
    
    @end
    

提交回复
热议问题