我的 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 触发的?
RoatedCommands
与 ApplicationCommands.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/