1
votes

I'm just getting started with unit testing and I'm wondering how to correctly test a NSDocument subclass?

In my test setUp I can init the document but that doesn't reflect how the document is setup when it's used by the app, specifically the IBOutlet connections aren't made and critical messages such as - (void)windowControllerDidLoadNib:(NSWindowController *)aController aren't called.

So what's the correct way to get a fully initialized NSDocument object for use in testing?

1

1 Answers

0
votes

This is how you can start:

#import <Cocoa/Cocoa.h>
#import <XCTest/XCTest.h>
#import "Document.h"

@interface DocumentTests : XCTestCase {
  Document *document;
  NSWindowController *controller
}
@end

@implementation DocumentTests

- (void)setUp {
  document = [[Document alloc] init];
  [document makeWindowControllers];
  controller = (NSWindowController *)[document windowControllers][0];
}

- (void)testLoadingWindow
{
  XCTAssertNotNil(controller.window);
}

- (void)testTextFieldOutletsIsConnected
{
  [controller window];  //kick off window loading
  XCTAssertNotNil(document.textField);
}
  //For asynchronous testing use XCTestExpectation
  //[self expectationWithDescription:@"Expectations"];
  //[self waitForExpectationsWithTimeout:3.0 handler:nil];

Correct approach: Do not put any UI stuff into your document (windowControllerDidLoadNib) if you want to test it. Single responsibility. How? Just implement makeWindowControllers

- (void)makeWindowControllers
{
  CustomWindowController *controller = [[CustomWindowController alloc] init];
  [self addWindowController:controller];
}

From window controller you can access your document anytime

- (CustomDocument *)document
{
  return [self document];
}