简体   繁体   中英

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?

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM