【发布时间】:2011-04-01 09:11:31
【问题描述】:
我的粘贴命令在正常执行期间似乎可以工作,但在单元测试中,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);
}
}
【问题讨论】:
-
您是否尝试在
ViewModel.CanPasteExecute中设置断点?是否根本不调用它或忽略该值可能很重要。 -
@Florian:是的,断点没有被命中。
-
应该
RegisterCommandBinding(pasteBinding, typeof(LookupViewModel));实际上是RegisterCommandBinding(pasteBinding, typeof(ViewModel));吗? -
@Florian:又一个错字!我很抱歉。看看我是多么依赖编译器来解决我的粗心大意。
标签: c# wpf unit-testing icommand