我有一个ViewController,它符合协议。 ViewController具有以下私有UI组件:backgroundImage,logoimage,loginButton和signupButton-所有这些都是私有的。 (因此无法通过单元测试访问)
如何在单元测试中测试以下协议方法的实现?我正在使用XCTestFramework
进行单元测试。
extension ViewController : ViewControllerProtocol{
func setbackgroundImage(_ image: UIImage) {
backgroundImage.image = image
}
func setLogoImage(_ image: UIImage) {
logoImage.image = image
}
func setLoginButtontitle(_ title: String) {
loginButton.setTitle(title, for: .normal)
}
func setSignupButtonTitle(_ title: String) {
signupButton.setTitle(title, for: .normal)
}
}
protocol ViewControllerProtocol {
func setbackgroundImage(_ image : UIImage)
func setLogoImage(_ image : UIImage)
func setLoginButtontitle(_ title: String)
func setSignupButtonTitle(_ title: String)
func setTitleLabel(_ title: String)
func setContinuewithoutsignupTitle(_ title: String)
}
您仍然可以通过添加公共获取器对这些值进行单元测试
protocol ViewControllerProtocol {
func setbackgroundImage(_ image : UIImage)
func setLogoImage(_ image : UIImage)
func setLoginButtontitle(_ title: String)
func setSignupButtonTitle(_ title: String)
func setTitleLabel(_ title: String)
func setContinuewithoutsignupTitle(_ title: String)
func getbackgroundImage() -> UIImage?
func getlogoImage() -> UIImage?
func getloginButtonTitle() -> String?
func getsignupButtonTitle() -> String?
}
class MainTest: XCTestCase {
let viewController = ViewController()
override func setUp() {
super.setUp()
}
func testExample() {
guard let testImage1 = UIImage(named: "testImage1") else {
XCTFail("Could not load test image 1")
return
}
viewController.setbackgroundImage(testImage1)
XCTAssert(viewController.getbackgroundImage() == testImage1)
guard let testImage2 = UIImage(named: "testImage2") else {
XCTFail("Could not load test image 2")
return
}
viewController.setLogoImage(testImage2)
XCTAssert(viewController.getlogoImage() == testImage2)
viewController.setLoginButtontitle("test")
XCTAssert(viewController.getloginButtonTitle() == "test")
viewController.setSignupButtonTitle("test")
XCTAssert(viewController.getsignupButtonTitle() == "test")
}
}