我正在尝试为我的 View 模型编写一些单元测试,但遇到了以下问题。 部分问题是我可能错误地使用了服务定位器,但情况就是这样。
这是我的代码(使用 MVVM Light IOC 注册我的存储库):
public class TestViewModel : ViewModelBase
{
private RelayCommand ...;
private RelayCommand ...;
private ObservableCollection<Test> _list;
private IRepository<Test> _testRepository;
public TestViewModel()
{
//Get the repository
_tenderRepository = ServiceLocator.Current.GetInstance<IRepository<Test>>();
//do a get on the repository and load it onto a list
LoadTestData()
}
...
}
我想对此 View 模型进行单元测试的几个公共(public)属性和公共(public)方法......所以我以这种方式设置它:
[TestFixture]
public class VMTests
{
TestViewModel _vm;
[SetUp]
public void RunBeforeAllFixtures()
{
_vm = new TestViewModel();
}
[Test()]
public void PublicMethod()
{
...
}
}
当我尝试运行测试时,我从测试引擎收到一条错误消息,指出“必须设置ServiceLocationProvider”。这是否意味着我必须模拟(或创建测试提供程序),在测试项目中注册它,然后再在测试项目中创建选择虚拟机实例?
最佳答案
怎么样
[SetUp]
public void RunBeforeAllFixtures()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
_vm = new TestViewModel();
}
并且还模拟和注册 IRepository 'Test'
关于c# - 如何设置服务定位器来测试 MVVM 中的 View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26516230/