1

我编写的一个类使我的测试用例崩溃,错误代码为 138。该类返回一个 NSString,其中包含来自 UIWebView 的用户代理字符串:

@interface MyWebViewUserAgent : NSObject <UIWebViewDelegate> {
    NSString* userAgent;
    UIWebView* webView;
}

- (NSString*) userAgentString;

@end

#import "MyWebViewUserAgent.h"

@implementation MyWebViewUserAgent

- (NSString*) userAgentString {
    if (userAgent != nil) return userAgent;

    webView = [[UIWebView alloc] init];
    webView.delegate = self;
    [webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: @"http://127.0.0.1"]]];

    // Wait for the web view to load our bogus request and give us the secret user agent.
        while (userAgent == nil) {
        // This executes another run loop. 
        [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate: [NSDate distantFuture]];
    }

    NSString *currentDeviceType = [[UIDevice currentDevice] model];
    NSRange range = [userAgent rangeOfString:currentDeviceType];

    if (range.location == NSNotFound) {

        // Should only happen when iPhone-targeted app is running on an iPad.
        NSRange rangeToReplace = [userAgent rangeOfString:@"iPhone;"];
        if (rangeToReplace.length > 0) {
            userAgent = [userAgent stringByReplacingCharactersInRange:rangeToReplace withString:@"iPad;"];
        }
    }
    return userAgent;
}

- (BOOL) webView: (UIWebView*) web_view shouldStartLoadWithRequest: (NSURLRequest*) request navigationType: (UIWebViewNavigationType) navigation_type {
    userAgent = [request valueForHTTPHeaderField: @"User-Agent"];
    [webView release];
    return NO; // Return no, we don't care about executing an actual request.
}

- (void) dealloc {
    [super dealloc];
}

@end

现在,这是我的测试用例:

#import <SenTestingKit/SenTestingKit.h>
#import <UIKit/UIKit.h>
#import "MyWebViewUserAgent.h"

@interface MyUnitTests : SenTestCase {
    MyWebViewUserAgent *ua;
}

@end

@implementation MySDKUnitTests

- (void)setUp
{
    [super setUp];
}

- (void)tearDown
{
    // Tear-down code here.
    [super tearDown];
}

- (void)testUserAgentString {
    ua = [[MyWebViewUserAgent alloc] init];
    STAssertNotNil(ua, @"User agent object is nil.");
    STAssertNotNil([ua userAgentString], @"user agent string is nil");
    [ua release];
}

@end

STAssertNotNil测试中的第一个testUserAgentString工作正常,但第二个STAssertNotNil是使测试崩溃的行。有任何想法吗?

4

1 回答 1

0

您的项目没有为单元测试正确设置。尝试检查这些设置。如果失败,请尝试创建一个新项目,选择“包含单元测试”。

于 2012-11-03T02:42:51.333 回答