如何在ChildViewModel
中模拟ChildrenViewModel
的创建:
IChildViewModel c = new ChildViewModel(child);
children.Add(c);
我正在使用ChildViewModel
(没有ChildView
!),因为Child
(模型)类没有实现INotifyPropertyChanged
。 更新:我介绍ChildViewModel
封装Child
的原因之一是验证要求。 域模型对象应始终 有效(例如,孩子的名字不得包含数字)。但是,文本框应显示无效值。在这个非常简单的示例中,ChildrenView
由列出ChildViewModels
的DataGrid组成。用户可以在DataGrid“name”列中看到无效名称,但子对象始终有效。
ChildrenView
是一个用户控件:
<views:ChildrenView ChildrenAware="{Binding SelectedItem.ChildrenAware, Mode=OneWay}"/>
ChildrenViewModel
是在ChildrenView
:
<viewModels:ChildrenViewModel x:Key="ViewModel"/>
我的目标:我想测试ObservableCollection(类型参数为ChildViewModel
)是否填充了(模拟的)ChildViewModel
个对象。
问题:执行无参数构造函数为什么我不能使用构造函数注入(并注入一个可以创建ChildViewModel
s的组件)。
问题:我可以看到两个解决方案:使用属性注入或StaticClass
具有类型为IViewModelFactory
的set / get属性,我可以模拟:
var mockFactory = new Mock<IViewModelFactory>();
mockFactory.Setup(m => m.CreateChildViewModel(mockChild.Object))
.Returns(mockChildViewModel);
StaticClass.ViewModelFactory = mockFactory.Object;
还有其他人吗?我应该选择哪一个?
答案 0 :(得分:0)
问题:执行无参数构造函数的原因我无法使用 构造函数注入(并注入可以创建的组件) ChildViewModels)。
也许我并不完全理解你的问题。为什么不是你?
如果您的ViewModel
就像
public class ChildrenViewModel
{
public ChildrenViewModel()
{}
public ChildrenViewModel(IViewModelFactory<IChildViewModel> factory)
{
ChildViewModels = new ObservableCollection<IChildViewModel>(factory.Create());
}
public ObservableCollection<IChildViewModel> ChildViewModels { get; set; }
}
然后虚拟测试可能
[TestMethod]
public void ChildViewModelsCreatedTest()
{
var factory = new Mock<IViewModelFactory<IChildViewModel>>();
factory.Setup(f => f.Create())
.Returns(new List<IChildViewModel>() { new ChildViewModel() });
var vm = new ChildrenViewModel(factory.Object);
Assert.IsNotNull(vm.ChildViewModels);
Assert.IsTrue(vm.ChildViewModels.Count == 1);
}