我正在尝试为以下代码编写单元测试:
public static void AppExitCmdCanExecute(object sender,
CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}这段代码的问题是我不能创建CanExecuteRoutedEventArgs类型的模拟实例(密封类)或实例(内部构造函数)。
我尝试了下面的方法,但是下面的代码都抛出了运行时异常。
[Test()]
public void AppExitCmdCanExecuteTest()
{
object sender = null;
//Type to mock must be an interface or an abstract or non-sealed class.
var mockArgs = new Moq.Mock<CanExecuteRoutedEventArgs>();
AppCommands.AppExitCmdCanExecute(sender, mockArgs.Object);
Assert.IsTrue(mockArgs.CanExecute);
}
[Test()]
public void AppExitCmdCanExecuteTest()
{
object sender = null;
//Constructor on type 'System.Windows.Input.CanExecuteRoutedEventArgs'
// not found.
var mockArgs = Activator.CreateInstance(typeof (CanExecuteRoutedEventArgs),
BindingFlags.NonPublic |
BindingFlags.Instance,
new object[2] {fakeCommand,
fakeParameter});
AppCommands.AppExitCmdCanExecute(sender, mockArgs);
Assert.IsTrue(mockArgs.CanExecute);
}感谢您的关注。
发布于 2011-09-14 16:46:23
你用的是the wrong overload of CreateInstance。使用以下命令:
Activator.CreateInstance(typeof (CanExecuteRoutedEventArgs),
BindingFlags.NonPublic | BindingFlags.Instance, null,
new object[2] {fakeCommand, fakeParameter}, null);您需要确保fakeCommand不是null,因为构造函数对该参数有一个保护子句。
https://stackoverflow.com/questions/7413258
复制相似问题