Search code examples
objective-cunit-testingocmockito

Unit testing with OCMockito mocking UIImage


So I am attempting to start developing in a more test driven manner learning to use tests and such and as such i have already come across a vexing issue.

I would like to test that a function i pass an NSArray to then set's an exposed UIScrollview subview third index(first two are default for scroll insets) to be a UIImageView that contains a valid image.

The array i pass in will be of type ALAsset that the method will pull the image out. But i havent gotten that far.

So my first issue is...can i mock an UIImage to be valid i.e not nil in this scenario? or should how I write my tests be approached differently?

so far this is what i have tried

UIImage *mockImage = mock([UIImage class]);
UIImageView *imgView = [[UIImageView alloc]init];

[imgView setImage:mockImage];
NSArray *assets = @[imgView];
[SUT loadImagesForAssets:assets];

NSInteger firstViewIndexOddset = 2;
NSInteger idx = 0;

idx += firstViewIndexOddset;

UIImageView *imgViewFromSUT = [[SUT previewScrollView] subviews][idx];

XCTAssertNotNil(imgViewFromSUT.image);

Solution

  • Don't be seduced by mock object frameworks, not even OCMockito. When you're first starting with tests, I recommend not using any mocking framework. Instead, do it all yourself. After you get tired of typing similar things over and over, then see if a mock object framework will help.

    When I want a test that uses a valid UIImage, I use this:

    @implementation TestingImageData
    
    + (NSData *)validImageData
    {
        const char PNGbytes[] = "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A\x00\x00\x00\x0D\x49\x48\x44\x52\x00"
            "\x00\x00\x01\x00\x00\x00\x01\x01\x03\x00\x00\x00\x25\xDB\x56\xCA\x00\x00\x00\x03\x50\x4C"
            "\x54\x45\x00\x00\x00\xA7\x7A\x3D\xDA\x00\x00\x00\x01\x74\x52\x4E\x53\x00\x40\xE6\xD8\x66"
            "\x00\x00\x00\x0A\x49\x44\x41\x54\x08\xD7\x63\x60\x00\x00\x00\x02\x00\x01\xE2\x21\xBC\x33"
            "\x00\x00\x00\x00\x49\x45\x4E\x44\xAE\x42\x60\x82"; // 1x1 transparent pixel PNG
        size_t PNGlength = sizeof(PNGbytes) - 1;
        return [NSData dataWithBytes:PNGbytes length:PNGlength];
    }
    
    @end
    

    For example:

    [UIImage imageWithData:[TestingImageData validImageData]]