Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing NSDocument

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?

like image 226
user2180224 Avatar asked Jun 11 '26 16:06

user2180224


1 Answers

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];
}
like image 184
Marek H Avatar answered Jun 14 '26 04:06

Marek H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!