我正在尝试学习单元测试。以下是我第一次编写单元测试,用于比较从服务器返回的字符串。我确信我处理互联网连接的可用性和 nsnotification 的方式并不完美。测试 testGetURLEncodedString 总是打印 pass,因为其中没有 assert 语句。我不能把断言放在那里,因为我必须在收到响应后比较服务器返回的结果。任何人都可以请建议我纠正这样做的方法。
#import "MyAppTests.h"
@interface MyAppTests()
@property(nonatomic) AppDelegate *delegate;
@end
@implementation MyAppTests
@synthesize delegate = _delegate;
- (void)setUp
{
[super setUp];
self.delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if(![self.delegate internetConnectionAvailable])
{
STFail(@"Internet is not reachable.");
exit(-1);
}
}
- (void)tearDown
{
_delegate = nil;
[super tearDown];
}
- (void)testDelegate
{
STAssertNotNil(self.delegate, @"Cannot find the application delegate");
}
- (void)testGetURLEncodedString
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getURLEncodedStringSuccess:) name:@"getURLEncodedStringSuccess" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getURLEncodedStringFailed:) name:@"getURLEncodedStringFailed" object:nil];
[self.delegate getURLEncodedString:@"Testing Text"];
}
-(void)getURLEncodedStringSuccess:(NSNotification *)notification
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"getURLEncodedStringSuccess" object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"getURLEncodedStringFailed" object:nil];
STAssertTrue([[self.delegate getURLEncodedStringResponse] isEqualToString:@"Testing Text"], @"testGetURLEncodedString failed - did not receive expected response");
}
-(void)getURLEncodedStringFailed:(NSNotification *)notification
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"getURLEncodedStringSuccess" object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"getURLEncodedStringFailed" object:nil];
STFail(@"testGetURLEncodedString failed - server failed returning result");
}