测试特定图像是否已复制到粘贴板

我正在编写测试来validation将图像复制到粘贴板的function。

这是测试,因为我更喜欢写它:

// reset the paste board UIPasteboard.generalPasteboard.image = nil; //<-- this explodes XCTAssertNil(UIPasteboard.generalPasteboard.image); // Grab some random existing image UIImage *image = [UIImage imageNamed:@"some-image"]; MJKMyClass *myInstance = [[myInstance alloc] initWithImage:image]; [myInstance doSomethingThatCopiesImageToPasteboard] XCTAssertNotNil(UIPasteboard.generalPasteboard.image); 

这失败了:

 failed: caught "NSInvalidArgumentException", "-[UIPasteboard setImage:]: Argument is not an object of type UIImage [(null)]" 

这是令人惊讶的,因为根据UIPasteboard标题,图像是一个可以为空的字段。

 @interface UIPasteboard(UIPasteboardDataExtensions)  @property(nullable,nonatomic,copy) UIImage *image __TVOS_PROHIBITED;  @end 

我认为这意味着他们正在对参数进行运行时检查,即使它可以为空。

我尝试过的事情:

  • 按ID比较对象不起作用,因为UIImage是由generalPastboard.image复制的(每次调用UIPasteboard.generalPasteboard.image时都可以使用不同的实例)
  • 通过PNG表示进行比较可能有效,但似乎很粗糙。
  • 通过图像尺寸进行比较是迄今为止我最接近的赌注,但也似乎是迂回曲折。

您可以使用items属性清除粘贴板而不必传递nil

 UIPasteboard.generalPasteboard.items = @[]; 

或者在Swift中:

 UIPasteboard.generalPasteboard().items = [] 

要比较UIImages,您可能需要查看其他一些问题: