1

I am new to unit testing and am trying things out.

I created a view controller with 1 button (get sum), and 3 textfields (input 2 numbers and output the sum).

int aNum = [self.firstNumber.text intValue]; int bNum = [self.secondNumber.text intValue]; sum = aNum + bNum; self.total.text = [NSString stringWithFormat:@"%i", sum]; [self dismissKeyboard]; 

And my testing codes:

vc = [[TestingViewController alloc] init]; vc.firstNumber.text = @"1"; vc.secondNumber.text = @"2"; [vc getSum:nil]; STAssertTrue([vc.total.text isEqualToString:@"3"], @"total should be 3"); 

The test failed because I have tried to work with UI elements.

My questions is: is it possible to test with UI elements like this? How would I write a test to achieve this?

Thanks guys!

4 Answers 4

2

Yes, testing UI element in unit tests is definitely possible.

Techniques for this and more (including testing code which relies on networks) is covered in Test-Driven iOS Development (Developer's Library) by Graham Lee is a great resource: http://www.amazon.com/Test-Driven-iOS-Development-Developers-Library/dp/0321774183

Could be that the view isn't getting loaded. I had the same problem when I started with unit testing on iOS. Try calling [vc loadView]; after you init the viewcontroller.

vc = [[TestingViewController alloc] init]; [vc loadView]; 
Sign up to request clarification or add additional context in comments.

Comments

0

You need to load the NIB which is done by accessing the view (see iOS' view lifecycle):

vc = [[TestingViewController alloc] init]; // vc.firstNumber is nil right now, because the view isn't loaded [vc view]; // vc.firstNumber now exists vc.firstNumber.text = @"1"; vc.secondNumber.text = @"2"; [vc getSum:nil]; STAssertTrue([vc.total.text isEqualToString:@"3"], @"total should be 3"); 

Alternatively, if the view is part of a UIWindow hierarchy, you don't need to do this (ie - end-to-end testing)

Comments

0

You're trying to test a feature of your application while it runs. Do you understand the difference between unit tests and application tests? Did you read and obey the documentation on application tests? Are you running on the device?

Here's a helpful tutorial: http://cocoawithlove.com/2009/12/sample-iphone-application-with-complete.html

Comments

0

to test the UI, u can use javascript and that runs in Instruments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.