问题
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