0

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

1 回答 1

0

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

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

于 2012-08-16T05:51:24.933 回答