【问题标题】:Testing using reflection (PrivateObject)使用反射(PrivateObject)进行测试
【发布时间】:2012-01-13 01:17:23
【问题描述】:

我有一个小问题,但很烦人。

我正在使用 PrivateObject 进行一些测试以访问类中的各种方法。这一切都很好。但是,当方法签名包含“ref”时,ref 关键字似乎没有任何作用。

private bool NewDeviceArrivedDeviceAtWorkcenter(ThreadStartArgs args, ref Device deviceAtStation)
{
//..SomeCode
     deviceAtStation = null;
//...Method to test
}

此测试失败..

 [TestMethod]
        public void CheckForDeviceAtWorkcenterNoDeviceFound()
        {
Initialization omitted

var device = new Device();

            var result = accessor.Invoke("NewDeviceArrivedDeviceAtWorkcenter", 
                new []
                    {
                        typeof (ThreadStartArgs), 
                        typeof (Device).MakeByRefType()
                    }, 
                    new object[] 
                    {
                        threadStartArgs, 
                        device
                    });

            Assert.IsNull(device);
}

问题:为什么测试方法中的device obj没有设置为null?

任何帮助表示赞赏

亲切的问候 卡斯滕

【问题讨论】:

    标签: c# .net testing reflection ref


    【解决方案1】:

    通过传入 Invoke 的参数数组进行返回。

    [TestMethod]
    public void CheckForDeviceAtWorkcenterNoDeviceFound()
    { 
       //Initialization omitted for publicObject, threadStartArgs, device
    
       Type[] myTypes = new Type[] {typeof (ThreadStartArgs), 
                                    typeof (Device).MakeByRefType() };
       object[] myArgs = new object[] { threadStartArgs, device };
       string sMethod = "NewDeviceArrivedDeviceAtWorkcenter";
    
       //Invoke method under test
       bool bResult = (bool)publicObject.Invoke(sMethod, myTypes, myArgs);
    
       Device returnDevice = (Device)myArgs[1];
    
       Assert.IsNull(returnDevice);
    }
    

    【讨论】:

      【解决方案2】:

      根据this的回复,你应该得到你要测试的方法的MethodInfo,并用参数数组调用它。

      您是否尝试过仅使用typeof(Device) 调用该方法,而不使用MakeByRefType() 调用?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-19
        • 2011-01-29
        • 2020-01-19
        • 2023-03-06
        • 1970-01-01
        • 2021-04-14
        • 2017-10-31
        • 1970-01-01
        相关资源
        最近更新 更多