我尝试使用自定义ListView
为DataTemplate
编写单元测试。尽管在iOS和Android上按预期呈现单元格,但在运行NUnit测试时它们的绑定属性为null
。
设置
要在NUnit测试项目中启动Xamarin.Forms,我使用Xamarin.Forms.Mocks。所以TestFixture
看起来如下:
using NUnit.Framework;
using Xamarin.Forms;
using Xamarin.Forms.Mocks;
namespace UnitTest
{
[TestFixture]
public class Test
{
[SetUp]
public void SetUp()
{
MockForms.Init();
}
什么有用
一项运行良好的测试会创建一个新的DataTemplate
,其中自定义StringCell
绑定到字符串" foo":
class StringCell : ViewCell
{
public StringCell()
{
var label = new Label();
label.SetBinding(Label.TextProperty, ".");
View = label;
}
}
[Test]
public void ViewCellWithString()
{
var content = new DataTemplate(typeof(StringCell)).CreateContent();
(content as Cell).BindingContext = "foo";
Assert.That(((content as ViewCell).View as Label).Text, Is.EqualTo("foo"));
}
正如预期的那样,呈现的content
是一个ViewCell
View
类型Label
,Text
" foo"。
什么不起作用
然而,第二个测试失败:它创建DataTemplate
类型为ItemCell
的{{1}}绑定到自定义对象Item
,其中包含可绑定属性Name
" bar& #34;
class Item : BindableObject
{
public static readonly BindableProperty NameProperty = BindableProperty.Create(nameof(Name), typeof(string), typeof(Item), null);
public string Name {
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
}
class ItemCell : ViewCell
{
public ItemCell()
{
var label = new Label();
label.SetBinding(Label.TextProperty, nameof(Item.NameProperty));
View = label;
}
}
[Test]
public void ViewCellWithItem()
{
var content = new DataTemplate(typeof(ItemCell)).CreateContent();
(content as Cell).BindingContext = new Item { Name = "bar" };
Assert.That(((content as ViewCell).View as Label).Text, Is.EqualTo("bar"));
}
此测试失败,因为Label的Text
属性为null
。
我的问题
我做错了什么?不应该通过"."
绑定到字符串的行为类似于通过Item
绑定到NameProperty
的行为吗?或者是否有更好的方法来实例化具有绑定属性的列表视图单元格的视图以进行单元测试?
答案 0 :(得分:0)
我刚刚在代码中发现了一个微小而重要的错误:
而不是
label.SetBinding(Label.TextProperty, nameof(Item.NameProperty));
我需要写
label.SetBinding(Label.TextProperty, nameof(Item.Name));
因为nameof(Item.NameProperty)
会产生" NameProperty",但我需要绑定到" Name"。