2015-06-22 117 views
12

我正在使用XCTest在我的項目中編寫單元測試,並且在使用XCAssertNil()XCAssertNotNil()方法時,XCTest框架崩潰。XCTestAssertNil由於「無」參數導致崩潰

這裏是我的測試:

XCTAssertNotNil(messageCollection.fieldName, "field_name must be not-nil") 

這裏的堆棧跟蹤:

2015-06-22 17:05:17.629 xctest[745:8747] *** Assertion failure in void _XCTFailureHandler(XCTestCase *, BOOL, const char *, NSUInteger, NSString *, NSString *, ...)(), /SourceCache/XCTest_Sim/XCTest-7701/XCTestFramework/OtherSources/XCTestAssertionsImpl.m:41 
Test Case '-[Wakanda_iOS_Framework_Tests.WAKAdapterTest testEntityCollectionParsing]' started. 
2015-06-22 17:05:17.631 xctest[745:8747] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Parameter "test" must not be nil.' 

看來XCTest有一個名爲測試參數不能是零,奇怪預期的方法檢查零(或非零)的值...是否有其他人得到這個問題並解決了它?

+1

我有這個相同的錯誤,但對於不同的情況。我認爲問題在於我濫用測試API - 做異步測試,並在調用'expectation.fulfill()'後嘗試使用'XCTAssertEqual' *。我的猜測是,測試框架沒有注意到真正的問題,然後出現一個看似不相關的原因後來崩潰。 –

+0

是的 - 當你調用'expectation.fulfill()',然後命令一些異步代碼時,'XCTestCase'可能會被卸載。檢查我的答案以下@MattFenwick –

回答

2

既然你的「測試」是零,我猜你試圖從你寫的一個獨立函數中調用XCAssertNil作爲幫手。 XCTest聲明將self作爲「測試」,因此它們不能處於獨立函數中。他們必須在方法。嘗試將輔助函數更改爲方法。

+0

其實我已經在測試方法,和我的其他測試功能,如'XCTAssertEqual'正常工作... –

+0

奇怪。嘗試在您的測試方法中移動XCTAssertEqual。它在XCTAssertNil旁邊工作嗎? –

4

根據此rdar http://www.openradar.me/22409527,這似乎是XCTest中的一個錯誤,當您檢查爲零的可選項時會導致崩潰。

您可以解決您的測試:

XCTAssert(messageCollection.fieldName != nil, "field_name must be not-nil") 
+1

這似乎並不奏效,我仍然得到相同的錯誤。我使用Xcode 8。 –

+0

@MthetheDrill您準確使用了哪個版本的Xcode?剛剛在Xcode 8.2.1中測試過,XCTAssertNotNil()現在按預期工作,至少對我而言。 'var optional:String?' 'XCTAssertNotNil(可選,「field_name必須是非零」)' – florieger

2

正如我在XCTestAssertionsImpl.h看到:

XCT_EXPORT void _XCTFailureHandler(XCTestCase *test, BOOL expected, const char *filePath, NSUInteger lineNumber, NSString *condition, NSString * __nullable format, ...) NS_FORMAT_FUNCTION(6,7); 

這是第一個參數 - test - 指的XCTestCase實例。所以消息可能是:「嘿,你的XCTestCase對象不再存在,所以我不能調用它的任何方法」。

例如,當您在異步塊中調用某個XCTAssert...時可能會出現這種情況,可能會在封閉的XCTestCase對象消失後很長時間調用該異步塊。

如果這可能是一種情況,將[unowned self]添加到您的異步塊不會解決問題在這裏,您需要去期望或同步您的代碼。

0

同樣的錯誤了類似的情況發生這樣的:

let expectation = self.expectation(description: "exp") 

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { 
    expectation.fulfill() 
} 

DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { 
    XCTAssert(false) 
} 

waitForExpectations(timeout: 2, handler: nil) 

所以調用XCTAssert預期應驗了。
哪個課程是錯誤的。

+0

同樣的問題對我來說! – RoaflinSabos