单元测试MvxCommand的正确方法是什么?

时间:2016-02-21 14:34:16

标签: mvvmcross

我已经到了这个头发拉出舞台。我试图进行单元测试,调用时调度我的命令。首先,该命令在应用程序中运行良好,它只是测试失败。

我正在遵循mvvm交叉的n + 1天使用的模式,并检查了单元测试中其他帖子中提到的推荐git示例(Greg Shackles代码阵营等)。我正在使用Mvvm cross 4虽然这个问题也发生在3。

所以我的命令看起来像这样

private MvxCommand<IStation> itemSelectedCommand;

public System.Windows.Input.ICommand ItemSelectedCommand
{
    get
    {
        itemSelectedCommand = itemSelectedCommand ?? new MvxCommand<IStation>(DoSelectItem);
        return itemSelectedCommand;
    }
}

我有一个看起来像这样的模拟调度程序(来自代码阵营示例),它只是记录调用

    public class MockViewDispatcher : MvxMainThreadDispatcher, IMvxViewDispatcher
    {
        public IList<MvxViewModelRequest> ShowViewModelRequests = new List<MvxViewModelRequest>();
        public IList<MvxClosePresentationHint> CloseRequests = new List<MvxClosePresentationHint>();

        public bool ShowViewModel(MvxViewModelRequest request)
        {
            ShowViewModelRequests.Add(request);

            return true;
        }

        public bool ChangePresentation(MvxPresentationHint hint)
        {
            if (hint is MvxClosePresentationHint)
                CloseRequests.Add((MvxClosePresentationHint)hint);

            return true;
        }

        public bool RequestMainThreadAction(Action action)
        {
            action();

            return true;
        }
    }

我的单元测试如下

public class ReproduceProblemTests2 : MvxIoCSupportingTest
{
    protected MockViewDispatcher Dispatcher { get; private set; }
    protected IMvxMessenger Messenger { get; private set; }

    public ReproduceProblemTests2()
    {
        base.Setup();
    }

    [SetUp]
    public void SetUp()
    {
        MvxSingleton.ClearAllSingletons();
        ClearAll();

        Dispatcher = new MockViewDispatcher();
        Ioc.RegisterSingleton<IMvxMainThreadDispatcher>(Dispatcher);
        Ioc.RegisterSingleton<IMvxViewDispatcher>(Dispatcher);

        Messenger = new MvxMessengerHub();

        Mvx.RegisterSingleton<IMvxStringToTypeParser>(new MvxStringToTypeParser());
    }

    [Test]
    public void AllStationsViewModel_WhenAnItemIsSelected_ShouldExecuteCommand()
    {
        var item = new Mock<IStation>().Object;
        var service = new Mock<IStationService>();
        var sut = new AllStationsViewModel(service.Object);
        sut.ItemSelectedCommand.Execute(item);
        Dispatcher.ShowViewModelRequests.Any().Should().BeTrue();
    }
}

测试始终失败,调度程序永远不会调用。所以我猜我的布线是错误的,但我无法看到。我正在使用Nunit 2.6.4并且测试在VS跑步者和紧缩中都失败了所以它不是测试跑步者特定的。

任何人都知道我是什么类型的白痴?

0 个答案:

没有答案