我可以使用 moq Mock<MyClass> 吗?模拟一个类,而不是一个接口? [英] Can I use moq Mock&lt;MyClass&gt; to mock a class, not an interface?

查看:67
本文介绍了我可以使用 moq Mock<MyClass> 吗?模拟一个类,而不是一个接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览https://github.com/Moq/moq4/wiki/Quickstart,我看到了Mock一个界面.

Going through https://github.com/Moq/moq4/wiki/Quickstart, I see it Mock an interface.

我的遗留代码中有一个没有接口的类.当我 Mock 时,出现以下异常:

I have a class in my legacy code which does not have an interface. When I Mock<MyClass>, I get the following exception:

附加信息:无法实例化类的代理:MyCompnay.Mylegacy.MyClass.

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

如何使用 Moq 模拟遗留代码中的类?

How can I use Moq to mock class from legacy code?

推荐答案

Mock 具体类可能的

It is possible to Mock concrete 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());
  }

}

但是,

  • 必须是公共类
  • 被模拟的方法必须是虚拟的

我收到的消息:

使类成为内部

Castle.DynamicProxy.Generators.GeneratorException:MoqFixture+Foo 类型不是公开的.无法为不可访问的类型创建代理.

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

或者,有一个非虚方法

System.NotSupportedException:非虚拟(在 VB 中可覆盖)成员上的设置无效:mk => mk.GetValue()

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

与您的无法实例化消息不匹配,所以其他地方似乎有问题.

do not match your cannot instantiate message, so something else seems to be wrong.

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

If you do not have a default constructor on the mocked object you can get that error message

例如

public class Foo
{

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

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

可以通过将值传递到 Mock<> ctor 来解决这个问题

one can get around this by passing values into the Mock<> ctor

例如

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

这篇关于我可以使用 moq Mock<MyClass> 吗?模拟一个类,而不是一个接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆