c# - 为什么我的 Command.CanExecute 在单元测试中总是返回 false?

标签 c# wpf unit-testing icommand

我的 Paste 命令似乎在正常执行期间有效,但在单元测试中,CanExecute 方法始终返回 false

代码:

public class ViewModel
{
    public CommandBindingCollection CommandBindings { get; set; }
    public ICommand PasteCommand { get; set; }

    public ViewModel()
    {
        CommandBinding pasteBinding 
            = new CommandBinding(ApplicationCommands.Paste, Paste, CanPasteExecute);
        RegisterCommandBinding(pasteBinding, typeof(ViewModel));
        PasteCommand = (RoutedUICommand)pasteBinding.Command;
    }

    private void CanPasteExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }
    private void Paste(object sender, ExecutedRoutedEventArgs e)
    {
        // ...
    }
    private void RegisterCommandBinding(CommandBinding newCommandBinding, Type type)
    {
        if (CommandBindings == null)
            CommandBindings = new CommandBindingCollection();
        CommandManager.RegisterClassCommandBinding(type, newCommandBinding);
        CommandBindings.Add(newCommandBinding);
    }
}

单元测试:

[TestClass]
public class ViewModelTests
{
    private ViewModel _viewModel;

    [TestInitialize]
    public void Initialise()
    {
        _viewModel = new ViewModel();
    }

    [TestMethod]
    public void PasteTest()
    {
        // canExecute is always false somehow
        bool canExecute = _viewModel.PasteCommand.CanExecute(null);
        Assert.AreEqual<bool>(true, canExecute);
    }
}

最佳答案

我猜您在某个时刻将 CommandBindings 属性绑定(bind)到 UI 控件,并且该命令是从 UI 触发的?

RoatedCommandsApplicationCommands.Paste 类似,依赖于父 UI 元素上存在 CommandBinding,该元素位于触发命令的元素之上。该命令的 CanExucute 请求从调用该命令的控件(当前焦点或命令的目标)开始,并像 RoatedEvent 一样向上冒泡,寻找匹配的 CommandBinding。当它找到一个时,它会执行绑定(bind)中的 CanExecute 委托(delegate),以返回您正在查找的值。

由于测试中没有 UI,也没有命令的目标,因此调用命令的 CanExecute 将根本找不到委托(delegate),因此将返回 false。

所以,我认为如果没有 UI,您当前形式的测试将无法工作。

(我现在要去测试我的理论 - 稍后会编辑!)

关于c# - 为什么我的 Command.CanExecute 在单元测试中总是返回 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5511327/

相关文章:

unit-testing - Xcode 4 : Application Tests in iOS Simulator

unit-testing - 将 Generic.List 转换为 System.Threading.Task.Generic.List 时出现问题

c# - 在 Entity Framework EDMX 中创建 View 之间的关联时出错

c# - 更改访问修饰符解决方法

wpf - Windows8 或 wpf 中的颜色数组?

wpf - 为什么XAML Margin不遵循CSS规范?

c# - 空引用检查的良好做法是什么?

c# - 离开加入 Linq?

c# - 在哪里放置 WPF 动态控件创建代码

python - 使用 mock.patch 给我 AttributeError ("<module ' 包 1'' > 没有属性 'myfunc' “?