2

私の貼り付けコマンドは、通常の実行中に機能するようですが、単体テストでは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);
    }
}
4

1 に答える 1

4

CommandBindingsある時点でプロパティを UI コントロールにバインドし、コマンドが UI から起動されると思いますか?

RoutedCommandsコマンドが実行される親 UI 要素の上にあるApplicationCommands.Pasteことに依存します。CommandBindingコマンドのCanExucuteリクエストは、コマンドが呼び出されたコントロール (現在のフォーカスまたはコマンドのターゲット) から開始さRoutedEventれ、一致する を探すように上向きに泡立ちCommandBindingます。見つかった場合はCanExecute、バインディングからデリゲートを実行して、探している値を返します。

テストには UI がなく、コマンドのターゲットもないため、コマンドを呼び出してCanExecuteもデリゲートが見つからず、false が返されます。

したがって、現在の形式でのテストは、UI が存在しないと機能しないと思います。

(私は今、私の理論をテストするつもりです - 後で編集します!)

于 2011-04-01T09:37:52.163 に答える