Nitin Agrawal
Nitin Agrawal

Reputation: 1361

Moq callback method with object parameter

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.

Upvotes: 1

Views: 4515

Answers (1)

Nitin Agrawal
Nitin Agrawal

Reputation: 1361

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);
              });

Upvotes: 4

Related Questions