Home > Software design >  How to pass "dynamic" objects to mocked methods in MOQ
How to pass "dynamic" objects to mocked methods in MOQ

Time:08-17

i have a problem with the Moq framework. I try to setup a method which has an dynamic argument.

public class Cls
{
  public string Method(dynamic obj)
  {
    // do something
  }
}

When i try to mock this type


var mockCls = new Mock<Cls>();
mockCls .Setup(_ => _.Method(It.IsAny<object>())).Returns("Test");

but i`ve got an exception running the test

System.NotSupportedException : Unsupported expression: _ => _.Method(It.IsAny<object>())
Non-overridable members (here: Cls.Method) may not be used in setup / verification expressions.

Is there any way to handle this?

Best regards Daniel

CodePudding user response:

You need to make the method virtual in Cls

public class Cls
{
  public virtual string Method(dynamic obj)
  {
    // do something
  }
}

Alternatively you could use an interface like so:

public interface IMethodUser
{
    string Method(dynamic obj);
}

public class Cls : IMethodUser
{
  public string Method(dynamic obj)
  {
    // do something
  }
}

var mockMethodUser = new Mock<IMethodUser>();
mockMethodUser.Setup(x => x.Method(It.IsAny<object>())).Returns("Test");
  • Related