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?
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 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.
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.
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 .
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,
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With