刚开始使用 xcode 5 和 xctest。我如何测试按下按钮时加载 View 。我以编程方式添加了在单击 rightBarButtonItem 时调用的方法
action:@selector(onSettingsButton)
并在 onSettingsButton
-(void) onSettingsButton{
SettingsViewController *svc = [[SettingsViewController alloc] init];
[self.navigationController pushViewController:svc animated:YES];
}
如何编写 xctest 以确保 SettingsViewController 调出设置 View ?谢谢。
最佳答案
您需要一个交互测试——即检查对象之间交互的测试。在这种情况下,您想要测试 -pushViewController:animated:
在导航 Controller 上使用 SettingsViewController
调用。所以我们想将一个模拟对象放入 self.navigationController
中,我们可以问,“你是按预期调用的吗?”
我将为类取一个简单的名称:MyView。
我手动执行此操作的方法是子类化并覆盖 navigationController
。所以在我的测试代码中,我会做这样的事情:
@interface TestableMyView : MyView
@property (nonatomic, strong) id mockNavigationController;
@end
@implementation TestableMyView
- (UINavigationController *)navigationController
{
return mockNavigationController;
}
@end
现在,测试将创建一个 TestableMyView 并设置其 mockNavigationController
属性,而不是创建 MyView。
这个 mock 可以是任何东西,只要它响应 -pushViewController:animated:
并记录参数。这是一个简单的例子,手工操作:
@interface MockNavigationController : NSObject
@property (nonatomic) int pushViewControllerCount;
@property (nonatomic, strong) UIViewController *pushedViewController;
@property (nonatomic) BOOL wasPushViewControllerAnimated;
@end
@implementation MockNavigationController
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
self.pushViewControllerCount += 1;
self.pushedViewController = viewController;
self.wasPushViewControllerAnimated = animated;
}
@end
最后,这是一个测试:
- (void)testOnSettingsButton_ShouldPushSettingsViewController
{
// given
MockNavigationController *mockNav = [[MockNavigationController alloc] init];
TestableMyView *sut = [[TestableMyView alloc] init];
sut.mockNavigationController = mockNav;
// when
[sut onSettingsButton];
// then
XCTAssertEquals(1, mockNav.pushViewControllerCount);
XCTAssertTrue([mockNav.pushedViewController isKindOfClass:[SettingsViewController class]]);
}
这些事情可以通过使用模拟对象框架来简化,例如 OCMock、OCMockito 或 Kiwi 的模拟。但我认为首先从手开始会有所帮助,这样您才能理解这些概念。然后选择有用的工具。如果您知道如何手动完成,您就永远不会说:“模拟框架 X 不能满足我的需要!我被困住了!”
关于ios - xctest - 如何测试新 View 是否在按下按钮时加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20462288/