gpt4 book ai didi

ios - 如何对 Xcode 中断言失败的代码运行单元测试?

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:08:52 50 4
gpt4 key购买 nike

在 Xcode 中,我正在运行基于 ID 创建用户的测试。当设置了错误的 ID 时,测试应该会失败。虽然这个测试失败了,因为它测试的方法本身有断言:

[[Apiclient sharedClient] findAndCreateUserWithID:nil success:^(Player *player) {
STFail(@"should not be able to create player with no ID");
} failure:^(NSError *error) {

}];

调用的方法:

- (void)findAndCreateUserWithID:(NSNumber *)ID success:(void (^)(Player *))createdPlayer failure:(void (^)(NSError *error))failure
{
NSParameterAssert(ID);

当参数 ID 为 nil 时测试失败。我知道这是一个非常愚蠢的例子,因为它总是会失败,但是代码中已经有更多更有用的断言。什么是运行 Xcode 单元测试的最佳实践,哪些测试代码已经有断言?

最佳答案

截至 2014 年底,如果您正在使用新的测试框架 XCTest,您将需要使用 XCTAssertThrowsSpecificNamed 而不是旧的 STAsertThrowsSpecificNamed 方法:

void (^expressionBlock)() = ^{
// do whatever you want here where you'd expect an NSParameterAssertion to be thrown.
};

XCTAssertThrowsSpecificNamed(expressionBlock(), NSException, NSInternalInconsistencyException);

关于ios - 如何对 Xcode 中断言失败的代码运行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18735524/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com