MSTest PrivateType.InvokeStatic()抛出MissingMethodException

时间:2015-04-23 16:54:06

标签: c# mstest missingmethodexception

经过3个多小时的挫折后,我决定问。

我有这个简单的类要测试:

public class Organizer {
    private static bool Bongo(String p) {
        return p != null && p.Length >= 5;
    }

    private static int ValidateArgs(String[] args) {
        return args.Length;
    }
}

我使用MSTest来测试静态方法:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

public class OrganizerTest {
    [TestMethod]
    public void TestBongo() {
        PrivateType psOrganizers = new PrivateType(typeof(Organizer));

        // This one works fine.
        Assert.IsTrue(Convert.ToBoolean(psOrganizers.InvokeStatic("Bongo", "ABCDEFG")));

        // Fails with: "System.MissingMethodException: Method 'Organizer.Bongo' not Found.
        Assert.IsFalse(Convert.ToBoolean(psOrganizers.InvokeStatic("Bongo", null)));
    }

    [TestMethod]
    public void TestBodo() {
        PrivateType psOrganizers = new PrivateType(typeof(Organizer));

        String[] fakeArray = new String[] { "Pizza" };

        // Fails with: "System.MissingMethodException: Method 'Organizer.ValidateArgs' not Found.
        int result1 = Convert.ToInt32(psOrganizers.InvokeStatic("ValidateArgs", fakeArray));

        // Fails with: "System.MissingMethodException: Method 'Organizer.ValidateArgs' not Found.
        int result2 = Convert.ToInt32(psOrganizers.InvokeStatic("ValidateArgs", "A", "B", "C", "D"));

        // Fails with: "System.MissingMethodException: Method 'Organizer.ValidateArgs' not Found.
        int result3 = Convert.ToInt32(psOrganizers.InvokeStatic("ValidateArgs", new Object[] { "A", "B", "C", "D" }));

        Assert.IsTrue(result1 == 1 && result2 == 4 && result3 == 4);
    }
}

除了TestBongo中的第一个Assert之外,由于MissingMethodException,每个其他Assert都会失败。有很多InvokeStatic()重载,我怀疑编译器可能没有选择我期望的那个。

顺便说一句,请不要告诉我不要测试私人方法。我不是在寻找辩论。 :)

谢谢。

1 个答案:

答案 0 :(得分:3)

InvokeStatic的最后一个参数是params参数,因此对于这些情况,它的使用有点混乱。在第一种情况下,传递null似乎被视为尝试调用不带参数的方法。试试

psOrganizers.InvokeStatic("Bongo", new object[] { null })

使用null调用Bongo

在第二种情况下,由于array covarianceString[]可隐式兑换Object[]。字符串数组将作为参数列表而不是您想要的单个参数传递。您需要将字符串数组包装在另一个数组中以使其正常工作。尝试

psOrganizers.InvokeStatic("ValidateArgs", new object[] { new string[] { "A", "B", "C", "D" } })

调用ValidateArgs