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

爱⌒轻易说出口 提交于 2020-01-05 08:24:08

问题


Image Property:

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 { } 
    }
}

And the test method is:

[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);
}

And I've caught an error in Unit Testing:

Error in Assert.AreEqual. Expected: 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.

I cannot really understand where the difference between the same images is? Why is it not approved by the test?


回答1:


Two BitmapImage objects, even if created from the same image Uri, will not compare equal:

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

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

However, you could compare their UriSource properties or their string representations:

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


来源:https://stackoverflow.com/questions/31852372/the-same-image-is-not-equal-unit-testing-bitmapimage-property-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!