相同的图像是不相等的。单元测试。位图图像 属性。 C#

The same image is not equal. Unit Testing. BitmapImage Property. C#

图片属性:

public class SomeClass
{
  public BitmapImage Image 
   {
   get 
     {
       BitmapImage src = new BitmapImage();
       try
       {                        
         src.BeginInit();
         src.UriSource = new Uri(ReceivedNews.Image, UriKind.Absolute);
         src.CacheOption = BitmapCacheOption.OnLoad;
         src.EndInit();                        
        }
       catch { }
      return src;
      }
      private set { } 
    }
}

测试方法为:

[TestMethod]
public void CanPropertyImage_StoresCorrectly()
{            
   string address = "http://images.freeimages.com/images/previews/083/toy-car-red-1417351.jpg";
   var aSomeClass = new SomeClass(new News() { Image = address});
   BitmapImage src = new BitmapImage();
   try
     {
      src.BeginInit();
      src.UriSource = new Uri(address, UriKind.Absolute);
      src.CacheOption = BitmapCacheOption.OnLoad;
      src.EndInit();
     }
  catch { }
  Assert.AreEqual(src, aSomeClass.Image);
}

我在单元测试中发现了一个错误:

Assert.AreEqual 出错。预期:http://images.freeimages.com/images/previews/083/toy-car-red-1417351.jpg. In fact: http://images.freeimages.com/images/previews/083/toy-car-red-1417351.jpg.

完全看不懂同一张图的区别在哪里?为什么没有通过测试?

两个 BitmapImage 对象,即使从相同的图像 Uri 创建,也不会比较相等:

var imageUrl = "...";
var bi1 = new BitmapImage(new Uri(imageUrl));
var bi2 = new BitmapImage(new Uri(imageUrl));

Assert.AreEqual(b1, b2); // will fail

但是,您可以比较它们的 UriSource 属性或它们的字符串表示形式:

Assert.AreEqual(b1.UriSource, b2.UriSource); // will succeed
Assert.AreEqual(b1.ToString(), b2.ToString()); // will succeed