swiftunit-testingparameterized-unit-test

Parametrized unit tests in Swift


Is there any way to use parameterized unit tests, similar to what you can achieve in .Net using NUnit framework.

[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);
}

Using this kind of tests (vs non-parameterized ones) can give you bigger back for buck by allowing you to avoid writing series of almost identical unit tests differing only by parameter values.

I am looking for either XCTest-based solution or some other means to achieve it. Optimal solution should report each test case (parameter set) as a separate unit test in Xcode, so is it clear whether all or only some of the tests cases failed.


Solution

  • The best way to handle parameterized testing is to use XCTContext.runActivity. This allows to create a new activity with some name that will help you identify exactly which of the iterations failed. So for your division scenario:

    func testDivision() {
        let testCases = [
            (a: 12, b: 3, result: 4),
            (a: 12, b: 2, result: 6),
            (a: 12, b: 6, result: 1),
            (a: 12, b: 4, result: 3),
        ]
        for (a, b, result) in testCases {
            XCTContext.runActivity(named: "Testing dividing \(a) by \(b) to get result \(result)") { activity in
                XCTAssertEqual(result, a/b)
            }
        }
    }
    

    Note that after running the above test, case no. 1, 2 and 4 will succeed while case no. 3 will fail. You can view exactly which test activity failed and which of the assertions caused faiure in test report:

    Test activity with success and failure cases