我可以使用 moq Mock<MyClass> 来模拟 class,而不是接口吗?

Can I use moq Mock<MyClass> to mock a class, not an interface?

通过https://github.com/Moq/moq4/wiki/Quickstart,我看到它模拟了一个接口。

我的遗留代码中有一个 class 没有接口。当我 Mock<MyClass> 时,出现以下异常:

Additional information: Can not instantiate proxy of class: MyCompnay.Mylegacy.MyClass.

如何使用 Moq 从遗留代码中模拟 class?

可以模拟混凝土 classes

[TestClass]
public class PlaceholderParserFixture
{

  public class Foo
  {
     public virtual int GetValue()
     {
        return 11;
     }
  }

  public class Bar
  {
     private readonly Foo _foo;

     public Bar(Foo foo)
     {
        _foo = foo;
     }

     public int GetValue()
     {
        return _foo.GetValue();
     }
  }

  [TestMethod]
  public void MyTestMethod()
  {
     var foo = new Mock<Foo>();
     foo.Setup(mk => mk.GetValue()).Returns(16);
     var bar = new Bar(foo.Object);

     Assert.AreEqual(16, bar.GetValue());
  }

}

但是,

  • 必须是public class
  • 被模拟的方法必须是虚拟的

我收到的消息:

使class成为内部

Castle.DynamicProxy.Generators.GeneratorException: Type MoqFixture+Foo is not public. Can not create proxy for types that are not accessible.

或者,有一个非虚方法

System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: mk => mk.GetValue()

与您的cannot instantiate消息不符,所以似乎有其他问题。

如果模拟对象上没有默认构造函数,您会收到该错误消息

例如

public class Foo
{

    private int _value;
    public Foo(int value)
    {
       _value = value;
    }

    public virtual int GetValue()
    {
        return _value;
    }
}

可以通过将值传递给 Mock<> ctor

来解决这个问题

例如

var foo = new Mock<Foo>(MockBehavior.Strict, new object[] { 11 });