2010-12-02 82 views
2

我是新來的objective-c,我發現我不知道如何正確地聲明文本屬性on一些給定的標籤等於原始字符串值。我不確定是否需要將標籤轉換爲NSString,或者是否需要直接修改我的斷言語句。如何聲明一個UILabel.text屬性等於NSString的一個實例在objective-c

@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類型)它失敗。任何幫助將非常感激!

+0

注意:儘管最終結果是相同的,但它更習慣於以`[controller doMagic]`的方式調用您的方法。 – 2010-12-07 07:05:06

回答

2

您需要加載視圖控制器的筆尖。否則,將不會有任何物品讓標籤出口被連接到。要做到這一點

的一種方法是對於視圖控制器的視圖伊娃添加到您的測試用例:

@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 

請注意,您還需要從內你適當地調用超類的-setUp-tearDown方法。

最後,不要在方法調用中使用點語法,它不是消息表達式中括號語法的通用替換。使用點語法只有用於獲取和設置對象狀態。

7

STAssertEquals()檢查身份的兩個值提供的,所以它相當於這樣做:相反

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

,你想STAssertEqualObjects(),將實際運行isEqual:檢查類似如下:

STAssertTrue([@"hehe" isEqual:controller.label.text], ...); 
+0

我仍然使用isEqual:語法在控制檯中獲得相同的輸出(失敗的測試) - 當我嘗試測試IBOutlet項目時,我錯過了其他任何東西? – 2010-12-07 18:49:46

相關問題