C#当参数数量相等时,如何使用System.Reflection调用私有重载方法

X3n*_*ntr 1 c# reflection mstest

我有一个叫做的课TicketManager.这个类有两个私有方法private void Validate(Ticket ticket)和一个重载private void Validate(TicketResponse ticketResponse).

当我使用BindingFlags没有指定时,Type[]我得到一个不明确的匹配异常.

以下代码是使用MSTest的单元测试.

//testing private validation method using reflection
    [TestMethod]
    [ExpectedException(typeof(TargetInvocationException))]
    public void Validate_TicketResponseIsInvalid_ReturnsValidationException()
    {
        //Arrange
        TicketManager ticketManager = new TicketManager(ticketRepository);
        Ticket t = new Ticket { AccountId = 1, Text = "How do I test a private method in C#?", TicketNumber = 5 };
        TicketResponse tr = new TicketResponse { Ticket = t, IsClientResponse = false, Date = DateTime.Now };

        //reflection
        MethodInfo methodInfo = typeof(TicketManager).GetMethod("Validate", new Type[] { typeof(TicketResponse) });
        object[] parameters = {tr};
        //Act
        methodInfo.Invoke(ticketManager, parameters); //throws NullReferenceException

        //Assert
        //assertion happens using attribute added to method
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

您需要使用允许您指定BindingFlags要指定的重载NonPublic.例如:

    MethodInfo methodInfo = typeof(TicketManager).GetMethod("Validate",
        BindingFlags.NonPublic | BindingFlags.Instance,
        null, new Type[] { typeof(TicketResponse) }, null);
Run Code Online (Sandbox Code Playgroud)

但是,在测试的上下文中,我想知道这是否应该实际上有一个公共API,或者至少有一个internalAPI(而不是private)并且[InternalsVisibleTo(...)]用来让你的测试套件访问它.