同样的图像是不相等的.单元测试.BitmapImage财产.c#
本文关键字:BitmapImage 财产 单元测试 图像 不相等 | 更新日期: 2023-09-27 18:06:42
图片属性:
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 -汽车-红色- 1417351. - jpg。事实上: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