Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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

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

like image 662
n179911 Avatar asked Mar 28 '17 17:03

n179911


People also ask

How do I mock a class without an interface?

Simply mark any method you need to fake as virtual (and not private). Then you will be able to create a fake that can override the method. Save this answer.

How do you mock a class in Moq?

How To Mock Something With Moq. As you can see from the code above, mocking an object is simple. Simply use Mock<> , passing the type you want to mock.

What can be mocked with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces.

Can you mock a concrete class?

In theory there is absolutely no problem mocking a concrete class; we are testing against a logical interface (rather than a keyword interface ), and it does not matter whether that logical interface is provided by a class or interface . In practice .


1 Answers

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

}

but,

  • It must be a public class
  • The method to be mocked must be virtual

The messages I got for:

Making the class internal

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

or, having a non-virtual method

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

e.g.

public class Foo
{

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

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

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

e.g.

var foo = new Mock<Foo>(MockBehavior.Strict, new object[] { 11 });
like image 200
AlanT Avatar answered Sep 28 '22 00:09

AlanT