简体   繁体   中英

Is it possible to use parameterised test case data with Xcode's XCTest Framework?

Something similar to the TestCaseAttribute that NUnit has , along the lines of:

[TestCase(12,3,4)]
[TestCase(12,2,6)]
[TestCase(12,4,3)]
public void DivideTest(int n, int d, int q)
{
  Assert.AreEqual( q, n / d );
}

Is it possible to provide parameterised test case data like this, in Xcode?

It does not look like XCTest has this built in, but there is project on GitHub aims to add this functionaltiy.

From their ReadMe:

KNMParametrizedTest adds support for parametrized test cases using the XCTest framework. Here is an example:

KNMParametersFor(testExample, @[ @"Hello", @"World" ]) - (void)testExample:(NSString *)word { NSString *result = [myUppercaser uppercaseString:word]; XCTAssertEqualObjects(result, [word uppercaseString], @"Uppercaser failed for word %@", word); }

It looks like the easiest way to install this is through CocoaPods.

Although XCTest doesn't offer a proper means of writing parameterized tests, I found a nice, simple workaround in page 46 of Godfrey Nolan's book Agile Swift which is to define an array of tuples containing the input and output values, and then to iterate through each item in the array, as follows:

func test_multiple() {
    let cases = [(4,3,12),(2,4,8)]
    cases.forEach {
         XCTAssertEqual(myCalculator.multiply($0, $1), $2)
    }
}

The only caveat with this approach that I can see is that you'll only get one entry in the test navigator / test report rather than one for each test case. But the time you'll save from not having to write the same test again and again (with only a slight variation in each test) is well worth it in my opinion.

If you want a nice message in the case of a failed test, you can easily get this by adding one more element to the tuple which represents the message to pass into the XCTAssertEqual call, as follows:

func test_multiple() {
    let cases = [(4,3,12,"4 times 3"),(2,4,8,"2 times 4")]
    cases.forEach {
         XCTAssertEqual(myCalculator.multiply($0, $1), $2, $3)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM