【问题标题】:Why don't the values in variables declared in @interface persist between methods in XCTest?为什么@interface 中声明的变量中的值不会在 XCTest 中的方法之间持续存在?
【发布时间】:2015-12-17 19:37:49
【问题描述】:

我正在 Xcode 中编写脚本来运行一些 UI 测试,我想使用一些全局变量。
我的第一次尝试是在@interface 中声明一个类型为strong 的变量,如下所示:

@interface Extended_Tests : XCTestCase
@property (strong) NSMutableArray *list;
@property (strong) NSString *name;
@end

但这没有用。
我最终使用了老式的 C 方法在方法之外声明变量。

我的问题是,为什么这不起作用?为什么变量中的值不能在所有方法中保持不变?

编辑: 我的方法:

- (void)testMultiUser1 {
    [[[XCUIApplication alloc] init] launch];
    XCUIApplication *app = [[XCUIApplication alloc] init];
    [app.buttons[@"Sign-in button"] tap];
    sleep(5);
    user1 = [app.staticTexts elementBoundByIndex:0].label;
    [app.otherElements[@"LibraryView"] tap];
    sleep(5);
    _list = [[NSMutableArray alloc] init];
    for(int i = 0; i < 3; i++){
        XCUIElementQuery *file1 = [[app.cells elementBoundByIndex:i] descendantsMatchingType:XCUIElementTypeStaticText];
        NSString *number = [file1 elementBoundByIndex:0].label;
        [_list addObject:number];
    }
    XCTAssert(_list);
}

我希望这会将变量保存到数组 _list 中,这样我就可以在另一种方法中使用它:

-(void)testMultiUser3{
    //Go into Library and make sure top 3 files are different from user1
    XCUIApplication *app = [[XCUIApplication alloc] init];
    [app.otherElements[@"LibraryView"] tap];
    sleep(5);

    NSMutableArray *user2files = [[NSMutableArray alloc] init];
    for(int i = 0; i < 3; i++){
        XCUIElementQuery *list1 = [[app.cells elementBoundByIndex:i] descendantsMatchingType:XCUIElementTypeStaticText];
        NSString *number = [list1 elementBoundByIndex:0].label;
        [user2files addObject:number];
    }
    XCTAssert(!([user2files[0] isEqualToString:_list[0]] && [user2files[1] isEqualToString:_list[1]] && [user2files[2] isEqualToString:_list[2]]));
    }

【问题讨论】:

  • 您发布的一小段代码没有声明任何变量。它声明了两个属性。也许您应该使用更相关的代码来更新您的问题,以显示您的实际操作并解释您遇到的确切问题。

标签: objective-c xctest


【解决方案1】:

您的问题是 XCTest 特有的。

运行的每个测试都在测试用例类的新实例中运行。在您的情况下,每个测试都会实例化一个新的 Extended_Tests 对象。这就是为什么如果您在一个测试中设置任何一个变量,您将不会在另一个测试中看到这些变化。

一般来说,最好不要依赖其他测试的副作用,因为您将无法自行运行这些测试。最好使用共享设置方法来设置状态并从两个状态中使用。

如果您绝对必须在测试之间共享变量,那么您可以将类静态方法(用 + 而不是 - 声明的那些)与静态变量一起使用,或者像您一样使用全局变量。

【讨论】:

  • Objective-C 没有类属性。不过它有类方法。
  • 是的,没错,但是您可以使用此处的任何一种方法来模拟它们:stackoverflow.com/questions/695980/…
  • 也许将您的答案改写为@NobodyNada 在技术上是正确的。然而,更好的参考可能是Setting Static Variables in Objective-C,但也许我有偏见;-)
  • 哦,我明白了。谢谢大家的帮助!
猜你喜欢
  • 1970-01-01
  • 2011-07-30
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
  • 2013-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多