简体   繁体   English

Swift单元测试,如果方法可以处理可选设置为nil

[英]Swift Unit Test if method can handle optional set to nil

This applies to a project with both ObjC and Swift, where the code I relate to is written and tested in Swift. 这适用于同时具有ObjC和Swift的项目,其中与我相关的代码是在Swift中编写和测试的。

I have a communicator class which receives a document object and from that object should retrieve a documentId. 我有一个通信器类,它接收一个文档对象,并且应该从该对象中检索documentId。 My communicator has a serverPathForDocument: method, which uses this documentId to build a remote path to fetch relevant data. 我的沟通者有一个serverPathForDocument:方法,该方法使用此documentId来构建远程路径以获取相关数据。

Writing unit tests for the communicator I realised I wanted to know if my serverPathForDocument: method can handle a non-initiated (nil) value on the documentId. 为通信器编写单元测试,我意识到我想知道我的serverPathForDocument:方法是否可以处理documentId上未初始化的值(nil)。 If written in Obj-C my test would look something like: 如果用Obj-C编写,我的测试将类似于:

- (void)testThatRemotePathForDocumentCanHandleNilDocumentId {
   testDocument.documentId = nil
   XCTAssertNoThrow([sut serverPathForDocument: testDocument], "Method should handle nil argument");
}

Swift doesn't have exception, or so I've read, so how would I write a proper unit test that checks if a method can handle an optional set to nil? Swift没有异常,或者我已经读过,所以我将如何编写适当的单元测试来检查方法是否可以处理可选的nil设置?

I would probably want the serverPathForDocument method to return an optional path object (whatever it means for you). 我可能希望serverPathForDocument方法返回一个可选的路径对象(对您而言意味着什么)。 It would then be the responsibility of the caller to make sure the optional isn't nil and really represents a path. 然后,调用方有责任确保可选值不为nil并且确实代表路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM