1
votes

In my scenario I want to mock 1 of the service framework method which takes object parameter and reset it with strongly typed class object.

 public void Updatedata(object pvm)
    {
        var vm = new datamodel()
            {
                name = "test",
                age = 100
            };
        pvm = vm;
    }

It gives compilation error "Invalid callback. Setup on method with parameters (Object) cannot invoke callback with parameters (datamodel)." with below code for mocking.

 mockderived.Setup(p => p.Updatedata(It.IsAny<datamodel>()))
             .Callback<datamodel>(p =>
                 {
                     p.name ="My name is test";
              });

The mock works fine if I change my updatedata method to accepts datamodel as parameter instead of object type. To avoid compilation errors I changed code by passing object as parameter:

  mockderived.Setup(p => p.Updatedata(It.IsAny<object>()))
             .Callback<object>(p =>
                 {
                     p = new datamodel() {name = "My name is test"};
              });

Code get executed by it did not reulted in change of values of datamodel as expected.

1
What is the expected behavior, the way the method is declared will do nothing to the pvm outside of the object. Did you meant (out object pvm)? - Sunny Milenov
@SunnyMilenov you are right in general approach it should not do anything. Also the updatemethod is part of framework so not aware of exact implementation done there (above I wrote was fake implementation). As i m just writing unit test cases for existing working project so did not thought about it initially. But now even I am feeling confused how it is working without out parameter. - Nitin Agrawal
In framework api, they have used reflection and set properties of the object. It works without using out keyword. - Nitin Agrawal

1 Answers

3
votes

After using reflection to set properties of the object parameter in the callback method, I am able to mock method proerly.

   mockderived.Setup(p => p.Updatedata(It.IsAny<object>()))
             .Callback<object>(p =>
                 {
                     var temp = new datamodel();
                     var t = temp.GetType();
                     var nameprop = "no name";
                     var prop = t.GetProperties();
                     prop[0].SetValue(p, nameprop, null);
              });