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

时间:2018-08-01 10:39:24

标签: 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
    }

1 个答案:

答案 0 :(得分:5)

您需要使用重载来指定BindingFlags,以指定NonPublic。例如:

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

但是,在测试的上下文中,我想知道它是否应该实际上具有公共API,或者至少具有internal API(而不是private)并使用[InternalsVisibleTo(...)]让您的测试套件访问它。