0

Problem : Retrieving from NSBundle returns (null) while running Unit Test, returns valid object on run time.

What have I done ?

I have searched SO with similar problems, apple's developer and other online resources for this problem but with no luck.

I have tried solution from SO questions; OCUnit & NSBundle, NSBundle pathForResource returns nil.

All solutions I went through online point out to one thing Bundle for run time and tests are different.

All of them recommend having

[NSBundle bundleForClass: [self class]];

instead of

[NSBundle mainBundle];    

Question : I don't understand if the above fix is with setter injection or in the source file itself. ? Is there any other way I can test the method getIpAdress ?

Code

Class that returns (null),

// iRNetworkingObject.m

@implementation iRNetworkingObject

-(NSString*) getIpAdress {
     NSDictionary *infoDict = [[NSBundle bundleForClass:[self class]] infoDictionary];
     NSString *lookUpAdress = [infoDict objectForKey:@"LookUpIpAdress"];
     return lookUpAdress;
}
@end

Test class

- (void) testGetIpAdress {

    iRNetworkingObject* networkingObject = [[iRNetworkingObject alloc] init];
    NSString* testCase = @"192.168.2.1";
    NSString* encondedString = [networkingObject getIpAdress]];

    STAssertTrue([testCase isEqualToString:encondedString], @"Not equal");
}
Community
  • 1
  • 1
Kishor Kundan
  • 3,135
  • 1
  • 23
  • 30

1 Answers1

2

bundleForClass: is important in test code, to make sure you get the application bundle instead of the test bundle. You shouldn't have to do that in production code.

Your key @"LookUpIpAdress" is misspelled. Is that the problem?

Jon Reid
  • 20,545
  • 2
  • 64
  • 95
  • Ok, so the production code can have `mainBundle` and I will have to use something like `setter injection` from the test code to pass the bundle ? Naa, spelling's fine, it is working for run time and I simplified my code in the question ;) – Kishor Kundan Mar 19 '13 at 04:17
  • There's no need for setter injection. The test should be able to verify the actual value. – Jon Reid Mar 19 '13 at 05:27
  • that is the problem, it is not. :( – Kishor Kundan Mar 19 '13 at 05:28
  • I copied your code. Works fine. Any failure is more descriptive if I use `STAssertEqualObjects([networkingObject getIpAdress], @"192.168.2.1", nil)`. – Jon Reid Mar 19 '13 at 05:50
  • yeah that tells me `(null) should be equal to 102.168.2.1`. is there anything else I might be missing ? – Kishor Kundan Mar 19 '13 at 06:26
  • Not in the code you've shown. I'd start adding some logging, and compare the logs between production & test. – Jon Reid Mar 19 '13 at 15:53
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/26473/discussion-between-kishor-kundan-and-jon-reid) – Kishor Kundan Mar 19 '13 at 15:54