iOS单元测试:如何设置/更新/检查firstResponder? [英] iOS unit test: How to set/update/examine firstResponder?

查看:81
本文介绍了iOS单元测试:如何设置/更新/检查firstResponder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何编写第一响应者单元测试?

How do you write first responder unit tests?

我正在尝试编写测试以确认方法将焦点提升到下一个文本字段。 controller UIViewController 的后代。但是这个探索性测试失败了:

I'm trying to write a test to confirm that a method advances focus to the next text field. controller is a descendant of UIViewController. But this exploratory test fails:

- (void)testFirstResponder
{
    [controller view];
    [[controller firstTextField] becomeFirstResponder];

    STAssertTrue([[controller firstTextField] isFirstResponder], nil);
}

第一行导致视图被加载,以便其出口到位。文本字段是非零的。但测试从未通过。

The first line causes the view to be loaded so that its outlets are in place. The text fields are non-nil. But the test never passes.

我猜测 becomeFirstResponder 没有立即设置第一个响应者,但要安排好以后再做。那么有一个很好的方法来对它进行单元测试吗?

I'm guessing that becomeFirstResponder doesn't set the first responder right away, but schedules it for later. So is there a good way to write a unit test against it?

在接受的答案中从评论中提取答案...... 让事情为短时间:

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]];

我还发现我需要创建一个UIWindow并将视图控制器的视图放入其中,如在最受欢迎的答案中说明。

I've also found I need to create a UIWindow and drop the view controller's view into it, as stated in the most-upvoted answer.

推荐答案

我想在主循环中以某种方式完成管理/更改第一个响应链,当UI更新时,准备下一个事件处理。如果这个假设是正确的,我只需要执行以下操作:

I guess that managing/changing the first responder chain is somehow accomplished in the main loop, when the UI is updated preparing for the next event handling. If this hypothesis is correct, I would simply do the following:

-(void)assertIfNotFirstResponder:(UITextField*)field {
    STAssertTrue([field isFirstResponder], nil);
}

- (void)testFirstResponder
{
     [controller view];
     [[controller firstTextField] becomeFirstResponder];
     [self performSelector:@selector(@"assertIfNotFirstResponder:") withObject:[controller firstTextField] afterDelay:0.0];
 }

注意:我使用0.0延迟,因为我只想要消息是放上事件队列并尽快发送。我需要一种方法来回到主循环,因为它的内务管理。在您的情况下,这不会产生任何实际延迟。如果您正在执行多个相同类型的测试,即通过反复更改作为第一响应者的控件,此技术应该保证所有这些事件与 performSelector

Note: I have used a 0.0 delay because I simply want that the message is put on the event queue and dispatched as soon as possible. I need just a way to get back to the main loop, for its housekeeping. This should produce no actual delay in your case. If you are executing several tests of the same kind, i.e. by repeatedly changing the control that is the first responder, this technique should guarantee that all of those events correctly ordered with the ones generated by performSelector.

如果从不同的线程运行测试,可以使用 - performSelectorOnMainThread:withObject:waitUntilDone:

If you are running your tests from a different thread, you could use – performSelectorOnMainThread:withObject:waitUntilDone:

这篇关于iOS单元测试:如何设置/更新/检查firstResponder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆