Objective-C 协议在 XCTest 中选择器失败,但在应用程序中失败 [重复]

Posted

技术标签:

【中文标题】Objective-C 协议在 XCTest 中选择器失败,但在应用程序中失败 [重复]【英文标题】:Objective-C protocol fails selector in XCTest, but not in app [duplicate] 【发布时间】: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 混淆了。他们是不一样的!类别扩展了现有的类。协议是一个类(通常是您正在编写的)必须实现的接口,以执行特定任务或一组任务。 【参考方案1】:

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

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

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

【讨论】:

以上是关于Objective-C 协议在 XCTest 中选择器失败,但在应用程序中失败 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 XCTest 测试一个 navigationBar 是不是未在 Objective-C 中设置为特定颜色?

将 XCTest 与 Objective-C++ 代码一起使用:“Unexpected @ in program”错误

用于单元测试 Objective-C XCTest 的 .m 文件中的访问变量定义

即使在 XCTest 文件中实现类扩展中的方法后,仍会调用协议的默认实现

XCTest:[UIApplication sharedApplication] 返回 nil

我在从另一个控制器中动态更新一个控制器中的 UILabel 时遇到问题。它需要对应于在objective-c中选中的复选框