我尝试对文本字段实施单元测试,以检查该文本字段是否为空,但出现错误Unexpectedly found nil while unwrapping an Optional value
。我正在使用Guard,但我不知道自己在做什么错。
这是我的代码:
class AdminPanelViewController: UITableViewController {
// Func to insert data from TextFields into CoreData
func insertProduct(){
guard let productName = productNameTextfield.text, productName != "" else{
SCLAlertView().showError(Constants.nameRequired, subTitle: Constants.messageNameRequired)
return
}
guard let productCategory = productCategoryTextField.text, productCategory != "" else{
SCLAlertView().showError(Constants.categoryRequired, subTitle: Constants.messageCategoryRequired)
return
}
guard let productPrice = productPriceTextfield.text, productPrice != "" else{
SCLAlertView().showError(Constants.priceRequired, subTitle: Constants.messagePriceRequired)
return
}
guard let productDescription = productDescriptionTextView.text, productDescription != ""else{
SCLAlertView().showError(Constants.descriptionRequired, subTitle: Constants.messageDescriptionRequired)
return
}
let product = Product(context: context) // Start inserting in Core Data
let productUUID = UUID().uuidString
product.id = productUUID
product.name = productName
product.category = productCategory
product.price = Float(productPrice)!
product.prodDescription = productDescription
appDelegate.saveContext() // End inserting and save the content in Core Data
resetAllFields()
SCLAlertView().showSuccess(Constants.done, subTitle: Constants.messageProductAdded)
}
}
// UNIT TESTING
import XCTest
@testable import ShoppingLand
class AdminPanelViewControllerTests: XCTestCase {
var collection: AdminPanelViewController!
// Test if ProductNameTextfield is empty
func testIfProductNameTextfieldIsEmpty(){
guard let productNameTextField = collection.productNameTextfield else{
XCTFail("Product name is required !")
return
}
productNameTextField.text = ""
XCTAssertEqual(productNameTextField.text, "Product name is required !")
}
}
如果您正在阅读本文,非常感谢您的时间!