问题
I have a simple Mac OS application that comes with the default MainMenu.xib
. In there I have a second window for preferences and a PreferencesWindowController
. I'd like to get the following test working:
@implementation TestPreferencesWindow
- (void)testProtectsUserPasswordByUsingAPasswordField
{
PreferencesWindowController *controller = [[PreferencesWindowController alloc] initWithWindowNibName:@"MainMenu"];
XCTAssertInstanceOf([[controller passwordField] class], NSSecureTextField);
}
@end
The problem is that [controller passwordField]
is not initialised (because the nib isn't loading?) so it always returns nil
.
How do I tell the nib to create all the bindings?
When I call [controller window]
is gives the error, and returns nil
:
Could not connect the action orderFrontStandardAboutPanel: to target of class PreferencesWindowController
For debugging I have tried the following:
NSBundle *bundle = [NSBundle mainBundle];
XCTAssertNotNil(bundle);
NSString *nibPath = [bundle pathForResource:@"MainMenu" ofType:@"nib"];
XCTAssertNotNil(nibPath);
PreferencesWindowController *controller = [[PreferencesWindowController alloc] initWithWindowNibPath:nibPath owner:self];
NSLog(@"%@ %@", [controller window], [controller passwordField]);
However it still prints (null) (null)
...
To get rid of the warning:
NSBundle *bundle = [NSBundle mainBundle];
XCTAssertNotNil(bundle);
NSString *nibPath = [bundle pathForResource:@"MainMenu" ofType:@"nib"];
XCTAssertNotNil(nibPath);
NSApplication *app = [NSApplication sharedApplication];
PreferencesWindowController *controller = [[PreferencesWindowController alloc] initWithWindowNibPath:nibPath owner:app];
NSLog(@"%@ %@", [controller window], [controller passwordField]);
No more warning, but still prints (null) (null)
.. I feel like I'm getting closer though...
回答1:
I got solution. Write below method in your .m file, and declare public in .h file
MyWindowController.m file
- (instancetype)initWithWindowNibPath:(NSString *)nibPath {
self = [super initWithWindowNibPath:nibPath owner:self];
if(self)
{
//initialize stuff
}
return self;
}
MyWindowController.h file
- (instancetype)initWithWindowNibPath:(NSString *)nibPath;
Now write your code:
NSBundle *bundle = [NSBundle mainBundle];
XCTAssertNotNil(bundle);
NSString *nibPath = [bundle pathForResource:@"MyWindowController" ofType:@"nib"];
XCTAssertNotNil(nibPath);
MyWindowController *controller = [[MyWindowController alloc] initWithWindowNibPath:nibPath];
NSLog(@"%@ %@", [controller window], [controller passwordField]);
This is works perfect for me.
Reason: owner value not properly set in initWithWindowNibPath method and therefore not set class's properties NSOutlet to nib's control.
来源:https://stackoverflow.com/questions/22086277/is-it-possible-to-unit-test-a-windowcontroller-thats-initialised-with-a-nib