Pregunta

I need to make my iOS lib compatible with iOS 6+, so I'm making it forward compatible with libraries that are available in iOS 7 which make my life easier (that'll eventually let me remove the older code).

For example, native base64 encoding is available in iOS 7+, so I do an check that looks like this (which I pulled from another SO question):

if([NSData respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
     // Do iOS 7 stuff
} else {
     // Break my head over iOS 6 compatibility
}

This seems to work fine, but how do I write unit test(s) to check for both situations? If I use the same if-else check in my unit test, that would defeat the purpose of the unit test, wouldn't it?

¿Fue útil?

Solución

So the only real way you'll be able to test that it works on both iOS 6 and iOS 7 is to run the tests on both versions. In light of this, write one unit test that tests the method, then have your CI infrastructure (Xcode Bots, Travis CI, etc) run the all tests for all iOS versions you support. One project that does tests this way is Subliminal, which currently runs tests on iOS 6 and 7 on both iPhone and iPad.

Edit:

In this example, you have one test that checks that the base64 decoding is done correctly. This method doesn't have any knowledge of what iOS version its running on–it just knows if the decoding worked correctly. You would setup your CI infrastructure to run this method on iOS 6 and 7 devices. When it ran on iOS 7 devices, if would test the YES branch of the if statement, and on iOS 6 it would test the NO branch of the if statement.

- (void)testEncoding
{
    NSData *base64EncodedData = [@"aGVsbG8=" dataUsingEncoding:NSUTF8StringEncoding];

    NSString *decodedString = [self decodeData:base64EncodedData];

    XCTAssert([decodedString isEqualToString:@"hello"], @"The base64 encoded string should decode to the word `hello`");
}

- (NSString *)decodeData:(NSData *)data
{
    if ([data respondsToSelector:@selector(base64EncodedDataWithOptions:)]) {

        return [[NSString alloc] initWithData:[[NSData alloc] initWithBase64EncodedData:data options:0]
                                     encoding:NSUTF8StringEncoding];
    } else {
        // Whatever method you use on iOS 6 to decode the base 64 data.
        return nil;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top