简体   繁体   English

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

[英]How to unit test a private static/shared method?

As per this answer to Unit testing private methods in C# I am using a PrivateObject to unit test private methods.根据对C#中单元测试私有方法的回答,我正在使用PrivateObject 对私有方法进行单元测试。 This generally works really well and is quite easy to use, however it doesn't appear to work if the method is Shared or Static .这通常工作得很好并且很容易使用,但是如果方法是SharedStatic ,它似乎不起作用。

I don't really want to make the method public (otherwise I wouldn't even be bothering with PrivateObjects but I'm failing to see another way.我真的不想公开该方法(否则我什至不会打扰 PrivateObjects 但我看不到另一种方式。

Example vb methods in class being tested:正在测试 class 中的示例 vb 方法:

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

Unit test code单元测试代码

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

Interested in answers in either C# or VB对 C# 或 VB 中的答案感兴趣

You could use PrivateType and InvokeStatic for this:您可以为此使用PrivateTypeInvokeStatic

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

If you want to pass parameters ByRef - for instance if the method under test looked something like this:如果你想传递参数ByRef - 例如,如果被测方法看起来像这样:

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

You can use this overload of InvokeStatic to get the results back:您可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM