如何对私有静态/共享方法进行单元测试?

根据this answerUnit testing private methods in C#,我正在使用PrivateObject对私有方法进行单元测试。通常,此方法确实很好用,并且很容易使用,但是如果方法是SharedStatic,则似乎无法正常工作。

我真的不想公开该方法(否则,我什至不会为PrivateObjects烦恼,但是我看不到其他方法。

正在测试的类中的示例vb方法:

    Private Sub SampleInstanceMethod(arg as Object)
        'Do something
    End Sub
    Private Shared Sub SampleSharedMethod(arg as Object)
        'Do something
    End Sub

单元测试代码

    Dim fooBarPO = New PrivateObject(GetType(FooBar))
    fooBarPO.Invoke("SampleInstanceMethod",{arg1}) ' Works
    fooBarPO.Invoke("SampleSharedMethod",{arg1}) ' Doesn't work

对C#或VB中的答案感兴趣

duanchongxixi 回答:如何对私有静态/共享方法进行单元测试?

您可以为此使用PrivateTypeInvokeStatic

    Dim foo = New PrivateType(GetType(TestClass))
    foo.InvokeStatic("SampleSharedMethod",{arg1})

如果您想传递参数ByRef-例如,被测方法看起来像这样:

    Private Shared Sub SampleSharedMethod(ByRef arg As String)
       arg += "abc"
    End Sub

您可以使用InvokeStatic的重载来获取结果:

    Dim foo = New PrivateType(GetType(TestClass))
    Dim params() As Object = {"123"}
    foo.InvokeStatic("SampleSharedMethod",params)

    Dim updatedValue = params(0) ' This would be 123abc in this example
本文链接:https://www.f2er.com/3124196.html

大家都在问