3

我正在尝试为以下代码编写单元测试:

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);
}

感谢您的关注。

4

1 回答 1

4

您使用了错误的CreateInstance. 用这个:

Activator.CreateInstance(typeof (CanExecuteRoutedEventArgs),
                         BindingFlags.NonPublic | BindingFlags.Instance, null,
                         new object[2] {fakeCommand, fakeParameter}, null);

您需要确保fakeCommandis not null,因为构造函数对该参数有一个保护子句。

于 2011-09-14T08:46:23.103 回答