谁能给我一个有关iOS Swift中单元测试的例子吗?

时间:2019-05-02 07:22:56

标签: ios swift unit-testing

我是iOS开发的新手,想学习单元测试。我想使用文本字段添加两个数字,并在单击操作时在标签中显示结果。谁能建议我如何对此进行单元测试?

2 个答案:

答案 0 :(得分:3)

这是一个简短的示例,但是您应该始终尝试多种不同的变体,好像它将是文本而不是数字和负数,大于int的数字等。

class AddingViewController: UIViewController {

    var sum = 0

    let textField1 = UITextField()
    let textField2 = UITextField()
    let button = UIButton()
    override func viewDidLoad() {
        super.viewDidLoad()
        button.addTarget(self, action: #selector(addNumbers), for: .touchUpInside)
    }

    @objc func addNumbers() {
        guard let number1 = Int(textField1.text!), let number2 = Int(textField2.text!) else {
            return
        }
        sum = number1 + number2
    }
}

class TestAddingViewController {

    let vc = AddingViewController()

    func testAddNumbers() {
        let number1 = 1
        let number2 = 2
        let sum = number1 + number2
        vc.textField1.text = "\(number1)"
        vc.textField2.text = "\(number2)"
        vc.button.sendActions(for: .touchUpInside)
        XCTAssertEqual(sum, vc.sum)
    }
}

如果viewController是来自情节提要的,则可以像通常调用情​​节提要的viewControllers一样调用它

let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "someViewController")

文本字段+按钮将为@outlets,按钮操作将为@IBAction而不是@objc func

答案 1 :(得分:0)

这是我的视图控制器类:

import UIKit

class ViewController: UIViewController {

   // MARK: ▼▼▼ IBOutlets ▼▼▼
   @IBOutlet weak var lblAnswer: UILabel!

   // MARK: ▼▼▼ Lifecycle methods ▼▼▼
   override func viewDidLoad() {
      super.viewDidLoad()
      lblAnswer.text = "\(calculateSum(num1: 5, num2: 10))"
   }

   // MARK: ▼▼▼ Methods ▼▼▼
   func calculateSum(num1: Int, num2: Int) -> Int {
      return (num1 + num2)
   }
}

对于单元测试类,我有:

import XCTest
@testable import Test

class TestTests: XCTestCase {

// MARK: ▼▼▼ Variables ▼▼▼
var num1: Int?
var num2: Int?
var testClass: ViewController?

// This is used to initialise your code:
override func setUp() {
    testClass = ViewController()
    num1 = 10
    num2 = 10
}

// This runs when test is complete:
override func tearDown() {
    testClass = nil
    num1 = nil
    num2 = nil
}

// Should begin with test so that it is recognised:
func testSumFunction() {
    let sum = testClass!.calculateSum(num1: num1!, num2: num2!)
    // The sum should be 20 for this to pass.
    XCTAssertTrue(sum == 20)
}
}

如果更改了函数的逻辑并且答案不等于20,则此测试将失败。