Hi everyone! I imported custom font in project. How can I test it with the text in the text field? For example I have text field with text = "Stack overflow", with font = UIFont(name: "Roboto-Regular", size: 17). How can I check that text = "Stack overflow" has font = UIFont(name: "Roboto-Regular", size: 17)? Have you any ideas, how to implement this in XCTest?
Extensions
import UIKit
extension UIFont {
static func robotoRegular (size: CGFloat) -> UIFont? {
return UIFont(name: "Roboto-Regular", size: size)
}
static func robotoBold (size: CGFloat) -> UIFont? {
return UIFont(name: "Roboto-Bold", size: size)
}
}
CodePudding user response:
Will you be unit testing a class which uses those fonts?
I would suggest that you have a custom label subclass which you expect to be that font. The class and tests would look like this:
class CustomLabelWithFont: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
setStyle()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setStyle() {
self.font = .robotoBold(size: 20)
}
}
The tests file would look like so
class TestTestTests: XCTestCase {
func testFontSetting() throws {
let customLabel = CustomLabelWithFont(frame: .zero)
XCTAssertEqual(customLabel.font, .robotoBold(size: 20))
XCTAssertNotEqual(customLabel.font, .systemFont(ofSize: 20))
}
}
You can also test your UIFont extension directly if you wish. There wouldn't be much utility in this aside from checking that the nobody has accidentally changed the font logic
func testFontItself() throws {
let expectedFont: UIFont = .robotoBold(size: 20)!
XCTAssertEqual(expectedFont, UIFont(name: "Roboto-Regular", size: 20))
}