如何在c#

时间:2016-02-22 19:21:55

标签: c# wpf unit-testing mvvm

我是C#和WPF的新手,所以我想从MVVM开始。 我有一个小的WPF应用程序,我想测试我的视图模型是否在Designer模式下创建(检查DesignerProperties);鉴于我有一个IDataService,它通过硬编码列表(设计时)或REST服务(运行时)向ViewModel提供数据。

有没有办法模拟或存根这个DesignerProperties对象来强制它成为一个或另一个状态?

提前致谢。

2 个答案:

答案 0 :(得分:3)

  

是否可以通过Mock或Stub这个DesignerProperties对象来强制使用   它是一个还是另一个国家?

没有。这是一个静态的类;除非你正在使用" Microsoft Fakes"否则你不能轻易地嘲笑它。或"输入模拟"。

但你可以为DesignerProperties创建一个抽象,说IDesignerProperties,它有你感兴趣的方法/属性并注入它。这样它现在只是一个界面;你可以像对待所有其他依赖项一样模拟它。

答案 1 :(得分:2)

您可以为静态类创建一个包装器。我对DesignerProperties课不熟悉,但我在下面创建了一个例子。另请参阅依赖注入/控制反转,以便于单元测试。

静态类

static class DesignerProperties
{
    public bool IsInDesigner { get; }

    public void DoSomething(string arg);
    // Other properties and methods
}

依赖注入和模拟的接口。 (您可以通过反映静态类来使用T4模板进行自动生成)

interface IDesignerProperties
{
    bool IsInDesigner { get; }

    void DoSomething(string arg);
    // mimic properties and methods from the static class here
}

运行时使用的实际类

class DesignerPropertiesWrapper : IDesignerProperties
{
    public bool IsInDesigner 
    {
        get { return DesignerProperties.IsInDesigner; } 
    }

    public void DoSomething(string arg)
    {
        DesignerProperties.DoSomething(arg);
    }

    // forward other properties and methods to the static class
}

单元测试的模拟课程

class DesignerpropertiesMock : IDesignerProperties
{
    public bool IsInDesigner { get; set; } //setter accessible for Mocking
}

用法

class ViewModel 
{
    private readonly IDesignerProperties _designerProperties;

    // Inject the proper implementation
    public ViewModel(IDesignerProperties designerProperties)
    {
        _designerProperties = designerProperties;
    }
}

我希望这会对你有所帮助。