I'm new to objective-c and I'm finding that I don't know how to correctly assert that a text property on some given label is equal to a raw string value. I'm not sure if I just need to cast the label as NSString or if I need to modify my assert statement directly.
@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
The implementation of my doMagic method is below
@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
The build is fine when I modify the assert to compare a raw NSString to another but when I try to capture the text value (assuming it's of type NSString) it fails. An开发者_StackOverflow社区y help would be much appreciated!
STAssertEquals()
checks for identity of the two values provided, so it's equivalent to doing this:
STAssertTrue(@"hehe" == controller.label.text, ...);
Instead, you want STAssertEqualObjects()
, which will actually run an isEqual:
check like the following:
STAssertTrue([@"hehe" isEqual:controller.label.text], ...);
You need to load the nib of the view controller. Otherwise there won't be any objects for the label outlet to be hooked up to.
One way to do this is to add an ivar for the view controller's view to your test case:
@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
Note that you also need to invoke super's -setUp
and -tearDown
methods appropriately from within yours.
Finally, do not use dot syntax for method invocation, it is not a generic replacement for bracket syntax in message expressions. Use dot syntax only for getting and setting object state.
精彩评论