首页 > 解决方案 > 属性字符串的 Swift 单元测试

问题描述

我想为属性字符串创建一个单元测试。这是我的代码

func setupMyLabel() {
    myLabel.isHidden = false
    let attributes = [NSAttributedString.Key.font: Style.FontBook.bold,
                      NSAttributedString.Key.foregroundColor: Theme.brand]
    if userConnected {
        myLabel.attributedText = NSAttributedString(string: "myLabel_longText".localized, attributes: nil)
            .replacingFields(["1": (replacement: "myLabel_firstPart".localized,
                                    attributes: attributes)])
    } else {
        myLabel.text = NSLocalizedString("myLabel_shortext", comment: "myLabel_shortext")
    }
}

这是我编写的单元测试,用于在用户未连接时进行测试,因为标签仅包含文本

import Nimble
import Quick
import Mockingjay 

context("When user is not connected"){
            it("should display my label, and label should contain shortText string"){
                disconnectUser()
                vc.setupMyLabel()
                expect(vc.myLabel.isHidden).to(beFalse())
                expect(vc.myLabel.text).to(equal(String.localizedStringWithFormat("myLabel_shortext".localized, "")))
            }
 }

但是当用户连接时,我有点坚持为属性编写单元测试!

context("When user is connected"){
                it("should display my label, and label should contain longText string"){
                    connectUser()
                    vc.setupMyLabel()
                    expect(vc.myLabel.isHidden).to(beFalse())
                    expect(vc.myLabel.attributedText).to(equal( .... ?? ))
                }
}

标签: swiftstringunit-testingnsattributedstringattributed

解决方案


推荐阅读