Search code examples
c#visual-studiomoqmstest

Change parameter using Moq


I have a method to unit test (GetEnterpriseInfo) which calls another method (GetAssetInfo) from a class AssetInfoManager.

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. I have used Callback for that. _mockAssetInfoManager is mock of property assetInfoManager in above code.

_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

assetInfoManager.GetAssetInfo(deviceManager, enterprise);

My requirement is to change that to mocked value inside Callback. Is it possible?


Solution

  • 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.