문제

I am a beginner in "iOS", as will become clear from this question!! I am writing unit tests for my iOS app. I am trying to set the UITextField from the test class. Every time I set the username textfield text from the test case it returns null. Is there no way I can do this? I don't really want to change the code in my controller class for a test!

All the examples online create an instance of a class and set the text like below except using @synthesize (which I thought wasn't needed in "iOS7"), why is it returning null?

Code in Controller.h :

 @property (nonatomic, retain) IBOutlet UITextField *username;

Test Case class :

  SignUpViewController *viewController = [[SignUpViewController alloc]init];
viewController.username.text = @"username@example.com";
username.text =null
도움이 되었습니까?

해결책

Since your property is declared using IBOutlet, I assume you're using storyboards for your views. If this is the case, then it's not an issue of the textField's text being nil, it's an issue of the whole textField being nil.

When a view controller is loaded from the storyboard, all your IBOutlets (provided they're hooked up correctly), are initialized for you. When running unit tests, there is no interaction with the storyboard, so your textField will not be initialized.

To get around this issue, you can create and assign the textField yourself:

SignUpViewController *viewController = [[SignUpViewController alloc]init];
viewController.username = [[UITextField alloc] init];
viewController.username.text = @"username@example.com";

Or, even better, you could take a look at OCMock, and create and assign a mock text field in your unit tests.

다른 팁

You need to load the view first.

SignUpViewController *viewController = [[SignUpViewController alloc]init];
[viewController view]; // !!
viewController.username.text = @"username@example.com";

Just because a property exists, doesn't mean the instance variable that backs it has been created. That particular UITextField is a reference to an object loaded from a NIB file (see the IBOutlet attribute),so you probably want to initialize the view controller using:

NSString *nibname = @"SignUpViewController";     // JUST GUESSING!
SignUpViewController *viewController = [[SignUpViewController alloc] initWithNibName:nibname
                                                                              bundle:nil];

To get around this issue, you can create and assign the view of view controller yourself in unit tests class by writing this: let _ = self.mockSubject.view

Here mockSubject is the viewController.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top