2

我是 Objective-c 的新手,我发现我不知道如何正确断言某个给定标签上的文本属性等于原始字符串值。我不确定是否只需将标签转换为 NSString 或者是否需要直接修改我的断言语句。

@interface MoreTest : SenTestCase {
  MagiczzTestingViewController* controller;
}

- (void) testObj;

@end

@implementation MoreTest

- (void) setUp
{
  controller = [[MagiczzTestingViewController alloc] init];
}

- (void) tearDown
{
  [controller release];
}

- (void) testObj
{
  controller.doMagic;

  STAssertEquals(@"hehe", controller.label.text, @"should be hehe, was %d instead", valtxt);
}

@end

我的 doMagic 方法的实现如下

@interface MagiczzTestingViewController : UIViewController {
  IBOutlet UILabel *label;
}

@property (nonatomic, retain) UILabel *label;
- (void) doMagic;

@end

@implementation MagiczzTestingViewController
@synthesize label;

- (void) doMagic 
{
  label.text = @"hehe";
}

- (void)dealloc {
  [label release];
  [super dealloc];
}

@end

当我修改断言以将原始 NSString 与另一个进行比较时,构建很好,但是当我尝试捕获文本值(假设它是 NSString 类型)时,它失败了。任何帮助将非常感激!

4

2 回答 2

7

STAssertEquals()检查提供的两个值的身份,所以它相当于这样做:

 STAssertTrue(@"hehe" == controller.label.text, ...);

相反,您想要STAssertEqualObjects(),它实际上会运行如下isEqual:检查:

 STAssertTrue([@"hehe" isEqual:controller.label.text], ...);
于 2010-12-02T01:57:16.420 回答
2

您需要加载视图控制器的 nib。否则标签出口将不会有任何物体可以连接。

一种方法是为视图控制器的视图添加一个 ivar 到您的测试用例:

@interface MoreTest : SenTestCase {
    MagiczzTestingViewController *controller;
    UIView *view;
}
@end

@implementation MoreTest

- (void)setUp
{
    [super setUp];

    controller = [[MagiczzTestingViewController alloc] init];
    view = controller.view; // owned by controller
}

- (void)tearDown
{
    view = nil; // owned by controller
    [controller release];

    [super tearDown];
}

- (void)testViewExists
{
    STAssertNotNil(view,
        @"The view controller should have an associated view.");
}

- (void)testObj
{
    [controller doMagic];

    STAssertEqualObjects(@"hehe", controller.label.text,
        @"The label should contain the appropriate text after magic.");
}

@end

请注意,您还需要从您的内部适当地调用 super-setUp和方法。-tearDown

最后,不要在方法调用中使用点语法,它不是消息表达式中括号语法的通用替代品。将点语法用于获取和设置对象状态。

于 2011-01-02T21:53:43.567 回答