c# - 如何设置服务定位器来测试 MVVM 中的 View 模型

标签 c# wpf unit-testing mvvm mvvm-light

我正在尝试为我的 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/

相关文章:

wpf - 数据绑定(bind)是否始终编码到 UI 线程?

c# - TreeView 的父节点之间的空间

java - 使用mockito在JUnit中模拟ReentrantReadWriteLock

c# - AutoFixture AutoMoq 不使用我的属性模拟

c# - 尝试计算两个角度之间的差异 (atan2)

c# - 在 Entity Framework 6.1.3 中调用 SaveChanges 时获取实体名称

c# - list 上应该包含哪些内容可以帮助开发优秀的 OO 软件?

wpf - 需要 WPF 渲染技巧

python - 如何在 python 中自动将十几个测试用例添加到测试套件中

c# - Automapper 不从包含单个可为空 bool 字段的源进行映射