【问题标题】:Objective-C protocol fails selector in XCTest, but not in app [duplicate]Objective-C 协议在 XCTest 中选择器失败,但在应用程序中失败 [重复]
【发布时间】:2016-03-25 21:00:18
【问题描述】:

我有一个奇怪的问题,即调用协议失败并出现无法识别的选择器,但相同的代码在应用程序本身中运行良好。有谁知道为什么会这样?这是我正在使用的。

MKPolygon+PointInPolygon.h

@import Foundation;
@import MapKit;

@interface MKPolygon (PointInPolygon)

- (BOOL)containsCoordinate:(CLLocationCoordinate2D)coordinate;

@end

MKPolygon+PointInPolygon.m

#import "MKPolygon+PointInPolygon.h"

@implementation MKPolygon (PointInPolygon)

- (BOOL)containsCoordinate:(CLLocationCoordinate2D)coordinate
{
    MKMapPoint mapPoint = MKMapPointForCoordinate(coordinate);
    MKPolygonRenderer *polygonView = [[MKPolygonRenderer alloc] initWithPolygon:self];
    CGPoint polygonViewPoint = [polygonView pointForMapPoint:mapPoint];
    BOOL returnResult = CGPathContainsPoint(polygonView.path, NULL, polygonViewPoint, NO);

    return returnResult;
}

@end

MKPolygon+PointInPolygonTests.m

#import <XCTest/XCTest.h>
#import "MKPolygon+PointInPolygon.h"

@interface MKPolygon_PointInPolygonTests : XCTestCase

@end

@implementation MKPolygon_PointInPolygonTests

- (void)testThatCoordinateIsNotInPolygon {
        //Canton
        CLLocationCoordinate2D outsidePolygonLocation = CLLocationCoordinate2DMake(40.798946, -81.378448);

        //Columbus Bounds
        CLLocationCoordinate2D nw = CLLocationCoordinate2DMake(40.0, -83.0);
        CLLocationCoordinate2D ne = CLLocationCoordinate2DMake(40.0, -82.0);
        CLLocationCoordinate2D se = CLLocationCoordinate2DMake(39.0, -82.0);
        CLLocationCoordinate2D sw = CLLocationCoordinate2DMake(39.0, -83.0);

        CLLocationCoordinate2D coords[] = {nw, ne, se, sw};

        MKPolygon *polygon = [MKPolygon polygonWithCoordinates:coords count:4];

        BOOL result = [polygon  containsCoordinate:outsidePolygonLocation];

        XCTAssertFalse(result);
}

对 [polygon containsCoordinate:outsidePolygonLocation] 的调用会导致无法识别的选择器错误。

如果我将上述测试方法代码正确复制到应用程序中 --- 没有 XCTAssertion --- 它工作正常。

我不知道发生了什么。我让其他一些人看过这个,他们也没有发现任何问题。

【问题讨论】:

  • 您的测试包没有在MKPolygon+PointInPolygon.m 文件中编译。在 Xcode 中检查该文件的目标列表,确保包含测试目标。
  • 就是这样。我没有将协议的实现文件添加到测试目标中。
  • 另外,您似乎将 [类别](developer.apple.com/library/ios/documentation/Cocoa/Conceptual/…) 与 protocol 混淆了。他们是不一样的!类别扩展了现有的类。协议是一个类(通常是您正在编写的)必须实现的接口,以执行特定任务或一组任务。

标签: ios objective-c unit-testing polygon xctest


【解决方案1】:

不应该将生产代码添加到您的测试目标。

相反,在您的 Other Linker Flags 中声明 -ObjC 以便它选择 category method 实现。欲了解更多信息,请参阅Objective-C categories in static library

如果设置正确,测试目标可以访问生产代码中的所有内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-24
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2014-06-11
    • 1970-01-01
    相关资源
    最近更新 更多