【问题标题】:How to write OCUnit Test Case如何编写 OCUnit 测试用例
【发布时间】:2013-01-18 06:47:07
【问题描述】:

我想使用 Apple 的默认 SenTestingKit 为以下方法编写单元测试:

- (NSDictionary*)getValueTags {
    return _tags;
}

- (NSString*)getFlag {
    NSString* jo = @"";
    for (NSString* key in _tags) {
        jo = [jo stringByAppendingFormat:@"%@=\"%@\"&", key, [_tags objectForKey:key]];
    }
    if ([jo length] > 0) {
        jo = [jo substringToIndex:[jo length] - 1];
    }
    return jo;
}

我使用了默认的 SenTesting

    - (void)setUp
    {
        [super setUp];

        // Set-up code here.
    }

    - (void)tearDown
    {
        // Tear-down code here.

        [super tearDown];
    }

-(void)testValueTags{

}

-(void)testGetFlag{

}

我是编写测试用例的新手,我需要一些关于编写测试用例的示例方法指南

【问题讨论】:

    标签: iphone testing ocunit


    【解决方案1】:

    一个测试用例有四个不同的阶段:

    1. 设置
    2. 运动
    3. 验证
    4. 拆掉

    其中一些阶段可以是空的。例如,如果您使用 ARC,大多数拆卸会自动发生。

    开始时,不要在setUp 或tearDown 方法中添加任何内容。只需编写一个单元测试。这是一个有效的例子。 (我要更改名称,因为 Objective-C 的习惯用法是不使用“get”这个词。所以不要使用getFlag,而是直接称它为flag。)我将调用类 `Example ,我将使用 ARC。我使用缩写“sut”来表示“被测系统”。

    - (void)testFlagGivenOneEntry
    {
        // set up
        Example *sut = [[Example alloc] init];
        [sut setTags:@{ @"key1" : @"value1" }];
    
        // execute & verify
        STAssertEqualObjects([sut flag], @"key1=\"value1\"", nil);
    }
    

    这是一项测试。让我们再添加一个。

    - (void)testFlagGivenTwoEntries
    {
        // set up
        Example *sut = [[Example alloc] init];
        [sut setTags:@{ @"key1" : @"value1",
                        @"key2" : @"value2" }];
    
        // execute & verify
        STAssertEqualObjects([sut flag], @"key1=\"value1\"&key2=\"value2\"", nil);
    }
    

    此时,我们有重复的代码:创建 sut.现在我们可以将变量提升为类的实例变量。然后我们在setUp 中创建它并在tearDown 中销毁它:

    @interface ExampleTest : SenTestCase
    @end
    
    @implementation ExampleTest
    {
        Example *sut;
    }
    
    - (void)setUp
    {
        [super setUp];
        sut = [[Example alloc] init];
    }
    
    - (void)tearDown
    {
        sut = nil;
        [super tearDown];
    }
    
    - (void)testFlagGivenOneEntry
    {
        [sut setTags:@{ @"key1" : @"value1" }];
        STAssertEqualObjects([sut flag], @"key1=\"value1\"", nil);
    }
    
    - (void)testFlagGivenTwoEntries
    {
        [sut setTags:@{ @"key1" : @"value1",
                        @"key2" : @"value2" }];
        STAssertEqualObjects([sut flag], @"key1=\"value1\"&key2=\"value2\"", nil);
    }
    
    @end
    

    有关更复杂的示例,请参阅Objective-C TDD: How to Get Started。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多