开发者

How to unit test CanExecuteRoutedEventHandler?

I am trying to write a unit test for the following code:

public static void AppExitCmdCanExecute(object sender,
                                        CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
}

The problem with this code is that I am not able to create a mock instance (sealed class ) or instance (internal constructor) of CanExecuteRoutedEventArgs type.

I tried the following, but both the following code throw run-time exception.

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

Thanks for your interest.


You used the wrong overload of CreateInstance. Use this:

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

You need to make sure that fakeCommand is not null, as the constructor has a guard clause for that parameter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜