Swift 中的参数化单元测试

2023-12-24

有没有什么方法可以使用参数化单元测试,类似于您可以在.Net中使用NUnit https://github.com/nunit/docs/wiki/TestCase-Attribute框架。

[TestCase(12, 3, 4)]
[TestCase(12, 2, 6)]
[TestCase(12, 4, 3)]
public void DivideTest(int expectedResult, int a, int b)
{
  Assert.AreEqual(expectedResult, a / b);
}

使用这种类型的测试(相对于非参数化测试)可以让您避免编写一系列几乎相同的单元测试,仅参数值不同,从而为您带来更大的回报。

我正在寻找基于 XCTest 的解决方案或其他一些方法来实现它。最佳解决方案应将每个测试用例(参数集)报告为 Xcode 中的单独单元测试,以便清楚是否全部或仅部分测试用例失败。


使用参数化的最佳方法是使用 XCTestCase 子类的属性defaultTestSuite。一个清晰的除法示例如下:

import XCTest

class ParameterizedExampleTests: XCTestCase {
    
    //properties to save the test cases
    private var array: [Float]? = nil
    private var expectedResult: Float? = nil
    
    // This makes the magic: defaultTestSuite has the set of all the test methods in the current runtime
    // so here we will create objects of ParameterizedExampleTests to call all the class' tests methodos
    // with differents values to test
    override open class var defaultTestSuite: XCTestSuite {
        let testSuite = XCTestSuite(name: NSStringFromClass(self))
        addTestsWithArray([12, 3], expectedResult: 4, toTestSuite: testSuite)
        addTestsWithArray([12, 2], expectedResult: 6, toTestSuite: testSuite)
        addTestsWithArray([12, 4], expectedResult: 3, toTestSuite: testSuite)
        return testSuite
    }
    
    // This is just to create the new ParameterizedExampleTests instance to add it into testSuite
    private class func addTestsWithArray(_ array: [Float], expectedResult: Float, toTestSuite testSuite: XCTestSuite) {
        testInvocations.forEach { invocation in
            let testCase = ParameterizedExampleTests(invocation: invocation)
            testCase.array = array
            testCase.expectedResult = expectedResult
            testSuite.addTest(testCase)
        }
    }

    // Normally this function is into production code (e.g. class, struct, etc).
    func division(a: Float, b: Float) -> Float {
        return a/b
    }
    
    func testDivision() {
        XCTAssertEqual(self.expectedResult, division(a: array?[0] ?? 0, b: array?[1] ?? 0))
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift 中的参数化单元测试 的相关文章

随机推荐