如何验证自定义向导对象中模拟视图的顺序

How to verify order of mocked views in custom wizard object

我有一个 WPF MVVM 应用程序,我需要在其中创建一个包含控制各种视图流的自定义向导类型的对象。该向导包含一个私有的内部类型列表,这些类型稍后会创建到实际项目中,并且具有操作您所在视图的方法。

向导非常好用;现在是对其进行单元测试以确保视图顺序正确的时候了。

向导有一个指定其视图顺序的初始化调用。 NextStep 和 PreviousStep 用于更改您当前所在的视图(它们实际上只是更新索引并引发 属性 changed 事件),并且外部对象通过 CurrentStep 属性 访问当前视图风景。它使用 StructureMap IContainer 来实例化这些视图。

public class WizardExample
{
    private IList<Type> _steps = new List<Type>();
    private int _currentStepIndex = 0;

    public void Initialize()
    {
        _steps.Add(typeof(FirstStepView));
        _steps.Add(typeof(SecondStepView));
        _steps.Add(typeof(ThirdStepView));
    }

    public UserControl CurrentStep
    {
        get
        {
            Type currentStep = _steps[_currentStepIndex];
            return IOCContainer.GetInstance(currentStep) as UserControl;
        }
    }

    public IContainer IOCContainer { get; set; }

    public void NextStep()
    {
        if(_currentStepIndex < _steps.Count - 1)
        {
            ++_currentStepIndex;
        }
    }

    public void PreviousStep()
    {
        if(_currentStepIndex > 0)
        {
            --_currentStepIndex;
        }
    }
}

我想执行的测试是这样的(我正在使用 Moq 和 MSTest):

[TestMethod]
public void TestFirstPageType()
{
    Wizard testWizard = new Wizard();
    Mock<FirstStepView> mockFirstStepView = new Mock<FirstStepView>();
    mockFirstStepView.SetupAllProperties();

    Mock<IContainer> mockContainer = new Mock<IContainer>();
    mockContainer.Setup(c => c.GetInstance<FirstStepView>()).Returns(mockFirstStepView.Object);

    testWizard.IOCContainer = mockContainer.Object;
    testWizard.Initialize();

    FirstStepView testView = testWizard.CurrentStep as FirstStepView;
    Assert.IsTrue(testView != null);
}

但是,当我去执行这个测试时,我得到以下错误:

'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Expcetion: The component 'Castle.Proxies.FirstStepViewProxy' does not have a resource identified by the URI '/MyDll;component/wizard/views/firststepview.xaml'

知道我做错了什么吗?

根据示例,您的设置

mockContainer.Setup(c => c.GetInstance<FirstStepView>()).Returns(mockFirstStepView.Object);

以及您的代码中调用的内容

return IOCContainer.GetInstance(currentStep) as UserControl;

不一样。

您的设置需要与测试中打算使用的设置相匹配。

mockContainer.Setup(c => c.GetInstance(typeof(FirstStepView)).Returns(mockFirstStepView.Object);

我的问题是我试图在不需要时模拟视图。我已经将我的测试代码更改为这个,现在我的测试 运行 很好。

[TestMethod]
public void TestFirstPageType()
{
    Wizard testWizard = new Wizard();

    Mock<IContainer> mockContainer = new Mock<IContainer>();
    mockContainer.Setup(c => c.GetInstance<FirstStepView>()).Returns(new FirstStepView());

    testWizard.IOCContainer = mockContainer.Object;
    testWizard.Initialize();

    FirstStepView testView = testWizard.CurrentStep as FirstStepView;
    Assert.IsTrue(testView != null);
}