用于比较服务器返回字符串的单元测试

时间:2012-08-05 21:58:45

标签: unit-testing ios5 ocunit

我正在尝试学习单元测试。以下是我第一次编写单元测试,用于比较从服务器返回的字符串。我确信我处理互联网连接的可用性和通知的方式并不完美。测试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");
}

1 个答案:

答案 0 :(得分:0)

调用服务器并检查响应的自动化测试更好地称为服务器的“验收测试”。但是它们应该与应用程序的单元测试目标保持在一个单独的目标中,因为单元测试需要非常快。保持它们快速的主要方法是避免任何真正的网络。而且这有点先进。

由于您刚刚开始使用OCUnit,我建议您从验收测试开始,因为它们通常难以编写并提供不太精确的反馈。相反,从最简单的测试开始,这些测试是模型逻辑的测试。我的Xcode TDD 101可能有助于学习单元测试的机制。