使用Moq更改参数



我有一个方法到单元测试(GetEnterpriseInfo(,它调用类AssetInfoManager中的另一个方法(GetAssetInfo(。

private EnterpriseInfo GetEnterpriseInfo()
{
//some code
//assetInfoManager is a public property,  deviceManager and enterprise are local variables
assetInfoManager.GetAssetInfo(deviceManager, enterprise);
//some code
}

我想测试这个方法,所以我模拟了AssetInfoManager,但我需要根据mock更改参数deviceManager。为此,我使用了Callback_mockAssetInfoManager是上述代码中属性assetInfoManager的mock。

_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

我能够从测试中看到_deviceManagerGlobal的变化,但当我调试实际代码时,我没有看到deviceManager在上发生变化

assetInfoManager.GetAssetInfo(deviceManager, enterprise);

我的要求是在Callback中将其更改为模拟值。有可能吗?

使用回调填充传递到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

即使在实际的代码中,分配一个新变量也不会做你想做的事情

最新更新