从模拟对象访问私有成员
Accessing private members from mocked object
在我的项目中,我们有一个用于集成测试的测试数据存储库。然后使用此存储库创建一个模拟工作单元,可以由被测试的方法调用。我在尝试访问以执行断言时遇到问题。
我想要断言的数据保存在 source
中
我一直在研究使用反射访问非 public 成员,但以下 returns null
:
PropertyInfo pInfo = vms.GetType().GetProperty("SourceInterface", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
用 source
替换 SourceInterface
也 returns null
有什么方法可以从 source
中检索 SourceInterface
对象?
编辑:
测试方法:
[TestMethod]
public void GetAllVMS_VMSReturned()
{
IEnumerable<SourceInterface> vms = controller.GetAllVMS();
Assert.IsTrue(vms.ToList().Count > 0); //Throws NullReferenceException
}
正在测试的方法:
public IEnumerable<SourceInterface> GetAllVMS()
{
return database.SourceInterfacesRepository.GetAll();
}
source
不是 属性 而是一个字段。这样做:
FieldInfo[] privateFields = vms.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
然后您可以根据需要过滤 privateFields
。
在我的项目中,我们有一个用于集成测试的测试数据存储库。然后使用此存储库创建一个模拟工作单元,可以由被测试的方法调用。我在尝试访问以执行断言时遇到问题。
我想要断言的数据保存在 source
我一直在研究使用反射访问非 public 成员,但以下 returns null
:
PropertyInfo pInfo = vms.GetType().GetProperty("SourceInterface", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
用 source
替换 SourceInterface
也 returns null
有什么方法可以从 source
中检索 SourceInterface
对象?
编辑: 测试方法:
[TestMethod]
public void GetAllVMS_VMSReturned()
{
IEnumerable<SourceInterface> vms = controller.GetAllVMS();
Assert.IsTrue(vms.ToList().Count > 0); //Throws NullReferenceException
}
正在测试的方法:
public IEnumerable<SourceInterface> GetAllVMS()
{
return database.SourceInterfacesRepository.GetAll();
}
source
不是 属性 而是一个字段。这样做:
FieldInfo[] privateFields = vms.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
然后您可以根据需要过滤 privateFields
。