[英]Change parameter using Moq
I have a method to unit test ( GetEnterpriseInfo
) which calls another method ( GetAssetInfo
) from a class AssetInfoManager
.我有一个单元测试方法(
GetEnterpriseInfo
),它从 class AssetInfoManager
调用另一个方法( GetAssetInfo
)。
private EnterpriseInfo GetEnterpriseInfo()
{
//some code
//assetInfoManager is a public property, deviceManager and enterprise are local variables
assetInfoManager.GetAssetInfo(deviceManager, enterprise);
//some code
}
I want to test this method so I mocked AssetInfoManager
but I need parameter deviceManager
to be changed according to mock.我想测试这个方法,所以我模拟了
AssetInfoManager
,但我需要根据模拟更改参数deviceManager
。 I have used Callback
for that.我为此使用了
Callback
。 _mockAssetInfoManager
is mock of property assetInfoManager
in above code. _mockAssetInfoManager
是上面代码中属性assetInfoManager
的模拟。
_mockAssetInfoManager.Setup(x => x.GetAssetInfo(It.IsAny<IDeviceManager>(), It.IsAny<EnterpriseInfo>()))
.Callback((IDeviceManager deviceManager, EnterpriseInfo enterpriseInfo) =>
{
//_deviceManagerGlobal is private global variable
_deviceManagerGlobal= new DeviceManager
{
DeviceName = "Test Device"
};
deviceManager = _deviceManagerGlobal;
})
.Returns(_assetInfoList); //_assetInfoList is private global variable
I am able to see _deviceManagerGlobal
change from the test but while I debug actual code I don't see deviceManager
changing on line我能够从测试中看到
_deviceManagerGlobal
更改,但是在调试实际代码时,我没有看到deviceManager
更改
assetInfoManager.GetAssetInfo(deviceManager, enterprise);
My requirement is to change that to mocked value inside Callback
.我的要求是将其更改为
Callback
内的模拟值。 Is it possible?可能吗?
Use the callback to populate the desired members of the parameter passed into the mock.使用回调填充传递给模拟的参数的所需成员。
_mockAssetInfoManager
.Setup(x => x.GetAssetInfo(It.IsAny<IDeviceManager>(), It.IsAny<EnterpriseInfo>()))
.Callback((IDeviceManager deviceManager, EnterpriseInfo enterpriseInfo) => {
deviceManager.DeviceName = "Test Device";
})
.Returns(_assetInfoList); //_assetInfoList is private global variable
Even in the actual code assigning a new variable wont do what you are trying to do.即使在实际代码中分配一个新变量也不会做你想做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.