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