[英]XCTest for test setter in model object
I have a model object with computed variables. 我有一个带有计算变量的模型对象。 now i want to test setter of the variable.
现在我想测试变量的setter。 i wrote a test case and it gives the following error
我写了一个测试用例,它给出了以下错误
XCTAssertEqual failed: ("nil") is not equal to ("Optional("example@gmail.com")") -
XCTAssertEqual失败:(“ nil”)不等于(“ Optional(” example@gmail.com“)”)-
bellow i have mentioned the test case which i wrote 在下面,我提到了我编写的测试用例
func testNetworkModelObjectSet() {
let testObject = ["network": ["first_name": "Dimuth", "last_name": "Lasantha", "business_email": "testemail@gmail.com", "currency": "USD", "language": "en-us", "category": "individual"]]
let network = HVConnection(data: testObject)
network.business_email = "example@gmail.com"
XCTAssertEqual(network.business_email, "example@gmail.com")
}
here i have mentioned the related model object variable 在这里我提到了相关的模型对象变量
class HVConnection: NSObject {
//private var _data: NSMutableDictionary
private var _data: NSMutableDictionary
// MARK:- Init
init(data: NSDictionary)
{
_data = NSMutableDictionary(dictionary: data)
}
var business_email: String? {
get {
if let businessemailObject = _data.objectForKey("network")?.objectForKey("business_email") {
return (businessemailObject as! String)
} else {
return nil
}
}
set {
_data = ["business_email": newValue!]
}
}
}
You are reading from _data["network"]["business_email"]
, but writing to _data["business_email"]
. 您正在从
_data["network"]["business_email"]
,但正在写入_data["business_email"]
。 You should either update the getter, or the setter, depending on specifications. 您应该根据规格更新吸气剂或设定器。
As a side note, you can rewrite the getter in a more shorter/readable manner: 附带说明一下,您可以用更短/更易读的方式重写getter:
get {
return _data["network"]?["business_email"] as? String
}
The optional chaining feature of Swift makes it very easy to check for nil in chain of method calls. Swift的可选链接功能使检查方法调用链中的nil非常容易。
Also note that the setter will crash the app if a nil
value is passed, as the forced unwrap crashes when trying to unwrap nils. 另请注意,如果传递了
nil
值,则setter将使应用程序崩溃,因为在尝试解开nil时,强制解开会崩溃。
by setting network.business_email = "example@gmail.com"
you are overriding the content of _data
with ["business_email": newValue!]
. 通过设置
network.business_email = "example@gmail.com"
您_data
使用["business_email": newValue!]
覆盖_data的内容。
This will cause the getter to return nil
since it will enter the else
case because _data.objectForKey("network")
is nil
. 这将导致吸气返回
nil
,因为它会进入else
,因为情况_data.objectForKey("network")
是nil
。 Hence, the behaviour is as expected. 因此,行为是预期的。
I have changed the setter as follows 我已按以下方式更改了设置器
set {
_data = ["network":["business_email": newValue!]]
}
Now the test case passed 现在测试用例通过了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.