如何测试 N 秒后是否未调用方法?

How to test if a method isn't called after N seconds?

我正在编写一些测试,我需要检查 "nothing happens" 当应用收到请求时,该请求必须被完全忽略。知道请求是否被忽略的方法是检查发送请求后必须接收任何内容的两个委托。

我不知道如何测试这个:

func testIgnore() {

    sut.message() {
        //this doesn't have to be called if test succeed
    }

    sut.appointment() {
        //this doesn't have to be called if test succeed
    }

    stub(isHost("test.com")) { (request: NSURLRequest) -> OHHTTPStubsResponse in
        let data = "specific data".dataUsingEncoding(NSUTF8StringEncoding)
        return OHHTTPStubsResponse(data: data!, statusCode: 200, headers: nil)
    }

}

有什么想法吗??我完全迷失了,因为我不能使用期望,因为如果期望超时,那是一个失败的测试,而这个场景将是一个成功的测试……

我需要等待例如 3 秒,如果块没有被调用则成功

在您不希望被调用的两个方法中添加 XCTFail(),这样如果它们被调用,您的测试就会失败。

然后简单的使用XCTest方法进行异步测试等待3秒,例如:

let exp = self.expectationWithDescription("3 seconds passed")
dispatch_after(…3 seconds…, dispatch_get_main_queue()) {
  exp.fulfill()
}
self.waitForExpectationsWithTimeout(4)

⚠️ 这是伪代码,因为我在 iPhone 上,所以很难在那里写长代码,而且我可能在方法名称中输入了一些错别字。根据需要进行调整。


PS:顺便说一句,我不明白这个问题与 OHHTTPStubs 有什么关系。你的问题是 "how to test if a method isn't called after N seconds"…