【问题标题】:Why is my class crashing my OCUnit test case with error code 138?为什么我的班级用错误代码 138 使我的 OCUnit 测试用例崩溃?
【发布时间】:2012-10-31 18:46:21
【问题描述】:

我编写的一个类使我的测试用例崩溃,错误代码为 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

testUserAgentString 测试中的第一个 STAssertNotNil 工作正常,但第二个 STAssertNotNil 是导致测试崩溃的行。有什么想法吗?

【问题讨论】:

  • RhythmWebViewUserAgentMyWebViewUserAgent 的子类吗?
  • 我的错误,我忘记在 alloc-init 中更改类名。固定。
  • 我刚刚用你的代码建立了一个项目,测试通过了。因此,这不是您的代码,而是您的项目设置中的其他内容。你还有其他有效的单元测试吗?
  • 不,这实际上是我迄今为止编写的第一个也是唯一一个测试用例。

标签: objective-c ios unit-testing ocunit


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多