0

I want to create a unit test for an attributed string. Here is my code

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")
    }
}

Here my unit test that I wrote to test when the user is not connected, since the label would contain only text

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, "")))
            }
 }

but I'm a little bit stuck to write the unit test for the attributed when the user is connected !

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( .... ?? ))
                }
}
  • It might help if you told us what unit testing framework you're using. – Caleb Jul 13 '21 at 16:03
  • @Caleb I'm using Quick & Nimble – Elitia Universe Jul 13 '21 at 16:12
  • 1
    This is no unit test. You are just trivially repeating your own code. And what is replacingFields??? – matt Jul 13 '21 at 16:22
  • 2
    You need to rewrite your code to be testable. Think inputs and outputs. – matt Jul 13 '21 at 16:30
  • Yes, this is not a unit test. You need to consider not "what function is doing?", but "what is the goal of the function?", why is it even a function? for instance if you want to know if label was formatted properly, you don't need to know if user is connected, you just need to know that given (e.g.) specific `myLabel_longText` + localization on input, you should get a specific text on the output. And the state of the user (connected or not) is probably more than label format, you may need to test it separately. – timbre timbre Jul 13 '21 at 17:17
  • @KirilS. Thank you for your comment. I'm not testing if the user is connected. I'm calling the function of connecting the user so that the label can be formatted, and then I'm testing if the label has the right string value. – Elitia Universe Jul 14 '21 at 17:16

0 Answers0