是否可以对用笔尖初始化的 WindowController 进行单元测试?

2024-02-27

我有一个简单的 Mac OS 应用程序,默认情况下MainMenu.xib。在那里我有第二个窗口用于偏好设置和PreferencesWindowController。我想让以下测试工作:

@implementation TestPreferencesWindow

- (void)testProtectsUserPasswordByUsingAPasswordField
{
    PreferencesWindowController *controller = [[PreferencesWindowController alloc] initWithWindowNibName:@"MainMenu"];
    XCTAssertInstanceOf([[controller passwordField] class], NSSecureTextField);
}

@end

问题是[controller passwordField]没有初始化(因为笔尖没有加载?)所以它总是返回nil.

如何告诉笔尖创建所有绑定?

当我打电话时[controller window]给出错误,并返回nil:

Could not connect the action orderFrontStandardAboutPanel: to target of class PreferencesWindowController

为了调试我尝试了以下方法:

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

但它仍然打印(null) (null) ...

要消除警告:

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

不再有警告,但仍然打印(null) (null)..我觉得我越来越接近了...


我得到了解决方案。在 .m 文件中写入以下方法,并在 .h 文件中声明 public

MyWindowController.m 文件

- (instancetype)initWithWindowNibPath:(NSString *)nibPath {
    self = [super initWithWindowNibPath:nibPath owner:self];
    if(self)
    {
        //initialize stuff
    }
    return self;
}

MyWindowController.h 文件

- (instancetype)initWithWindowNibPath:(NSString *)nibPath;

现在编写您的代码:

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

这对我来说非常完美。

Reason:所有者值未在 initWithWindowNibPath 方法中正确设置,因此未将类的属性 NSOutlet 设置为 nib 的控件。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以对用笔尖初始化的 WindowController 进行单元测试? 的相关文章

随机推荐