如何对WPF Triggeraction的invoke-Method进行单元测试

时间:2018-11-13 13:53:05

标签: wpf vb.net unit-testing

我无法理解如何对此类进行单元测试'Invoke-方法:

Option Strict On
Imports System.Windows.Interactivity

Public Class ViewErrorCounterAction
    Inherits TriggerAction(Of DependencyObject)

    Public Shared ReadOnly ViewErrorCounterProperty As DependencyProperty = DependencyProperty.Register("ViewErrorCounter",GetType(Integer),GetType(ViewErrorCounterAction))

    Sub New()
        ViewErrorCounter = 0 
    End Sub

    Public Property ViewErrorCounter As Integer
        Get
            Return CType(GetValue(ViewErrorCounterProperty), Integer)
        End Get
        Set
            SetValue(ViewErrorCounterProperty, Value)
        End Set
    End Property

    Protected Overrides Sub Invoke(parameter As Object)
        Dim e = CType(parameter, ValidationErrorEventArgs)
        If (e.Action = ValidationErrorEventAction.Added) Then
            ViewErrorCounter = ViewErrorCounter + 1
        ElseIf (e.Action = ValidationErrorEventAction.Removed) Then
            ViewErrorCounter = ViewErrorCounter - 1
        End If
    End Sub

End Class

我设法调用了invoke方法,还通过使用此代码传递了正确的参数,但是由于ValidationErrorEventArgs对象的构造函数是内部的,因此很难创建它:

Sub Invoke_ValidationerrorEventEinAufruf_ErrorCounterIst1()
    Dim _viewErrorCounterAction = New ViewErrorCounterAction
    dim _manualTrigger = New ManualTrigger
    _manualTrigger.Actions.Add(_viewErrorCounterAction)

    'This line won't work because the constructor is internal
    Dim ev = New ValidationErrorEventArgs(New ValidationError(Nothing, Nothing), ValidationErrorEventAction.Added)

    _manualTrigger.Invoke(ev)
    Dim result = _viewErrorCounterAction.ViewErrorCounter
    Assert.That(result, [Is].EqualTo(1))
End Sub

'with help of https://stackoverflow.com/a/12977944/2582968
Public Class ManualTrigger
    Inherits Interactivity.TriggerBase(Of DependencyObject)

    Public Sub Invoke(parameter As Object)
        Me.InvokeActions(parameter)
    End Sub
End Class

我尝试使用Activator.CreateInstance创建ValidationErrorEventArgs,但尚未成功。由于整个激活器故事在我看来都与普通的单元测试的复杂性相去甚远,因此,我希望获得关于如何最好地测试该代码的任何提示。如果只有激活器是我的选择,那么我很乐意提供有关如何创建ValidationErrorEventArgs-Object的帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用反射创建一个ValidationErrorEventArgs

Dim validationErrorEventArgsConstructorInfo As ConstructorInfo = GetType(ValidationErrorEventArgs) _
    .GetConstructors(BindingFlags.NonPublic Or BindingFlags.Instance) _
    .First()

Dim validationErrorEventArgsInstance As ValidationErrorEventArgs = validationErrorEventArgsConstructorInfo _
    .Invoke(New Object() {New ValidationError(New DataErrorValidationRule(), New Object()), ValidationErrorEventAction.Added})