简体   繁体   English

是否可以在 Xcode 的 XCTest 框架中使用参数化测试用例数据?

[英]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:类似于NUnit 具有TestCaseAttribute东西,如下所示:

[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?是否可以在 Xcode 中提供这样的参数化测试用例数据?

It does not look like XCTest has this built in, but there is project on GitHub aims to add this functionaltiy.看起来 XCTest 没有内置这个功能,但是GitHub 上有一个项目旨在添加这个功能。

From their ReadMe:从他们的自述文件:

KNMParametrizedTest adds support for parametrized test cases using the XCTest framework. KNMParametrizedTest 使用 XCTest 框架添加了对参数化测试用例的支持。 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.看起来最简单的安装方法是通过 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:尽管 XCTest 没有提供编写参数化测试的正确方法,但我在 Godfrey Nolan 的书Agile Swift 的第 46 页找到了一个不错的简单解决方法,它定义一个包含输入和输出值的元组数组,然后迭代数组中的每一项,如下所示:

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:如果您想要在测试失败的情况下收到一条不错的消息,您可以通过向元组添加一个更多元素来轻松获得它,该元素代表要传递到XCTAssertEqual调用的消息,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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