Stefan Claussen
Stefan Claussen

Reputation: 53

How to unit test custom implementation of drawRect

I am trying to write a test/s using XCTest to drive out the implementation of a custom implementation of the drawRect method and am unsure how to do this.

The code I am looking to have to write because of a test/s is as follows:

- (void)drawRect:(CGRect)rect
{
    CGPoint startOfHorizontalLine = (CGPointMake(1.0f, 0.0f));
    CGPoint endOfHorizontalLine = (CGPointMake(1.0f, 10.0f));

    UIColor * lineColour = [UIColor colorWithRed:40.0f/255.0f green:34.0f/255.0f  blue:34.0f/255.0f alpha:1.0f];
    [lineColour setStroke];

    UIBezierPath *horizontalLine = [UIBezierPath bezierPath];
    [horizontalLine moveToPoint:startOfHorizontalLine];
    [horizontalLine addLineToPoint:endOfHorizontalLine];
    [horizontalLine stroke];
}

If I need to use a mocking library, I have done some research into OCMock.

Thank you for the help.

Upvotes: 3

Views: 580

Answers (1)

Jeremy W. Sherman
Jeremy W. Sherman

Reputation: 36143

To test this, you'd probably do better to pull out the body to methods that build paths or configure the current drawing context. Testing then becomes decently straightforward:

  • For the ones that build paths, you can ask them for their path and then verify it's built as expected.
  • For the drawing context ones, you'd stand up a drawing context (probably a bitmap context) and verify that the expected changes to the context (like stroke width, join style, stroke or fill color, etc.) are effected by the method under test.

If that's not practicable, then you're probably looking at something more like gold master testing, where you get it drawing something that looks right, bless that as the "gold master" by saving the drawing output as an image, then set up the test suite to re-draw what should be the same image and compare the two. If it didn't turn out the same, then the test fails.

Upvotes: 1

Related Questions