4

I am trying out Moq, and I've gotten stuck in a very basic example. I want to mock a very simple interface IInput:

namespace Example
{
    public interface IInput
    {
        int SomeProperty { get; set; }
    }
} 

This seems like a very easy job. However, I get a compilation error when I try to mock it in the following test code:

using Moq;
using NUnit.Framework;

namespace FirstEniro._Test
{

    [TestFixture]
    class TestFirstClass
    {
        [Test]
        public void TestConstructionOk()
        {
            var mock = new Mock<IInput>();
            mock.Setup(r => r.SomeProperty).Returns(3);

            var x = new FirstClass(mock);

            Assert.That(x, Is.EqualTo(3));
        }
    }
}

The compiler says "cannot convert from Moq.Mock<Example.IInput> to <Example.IInput>. I can't see what I am doing wrong. Please help me

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
Morten
  • 3,778
  • 2
  • 25
  • 45

2 Answers2

12

Use Object property of mock to retrieve instance of mocked object.

   var x = new FirstClass(mock.Object);

In Moq framework Mock is not an instance of what you are mocking (like in Rhino Mocks).

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
3

Use Object property on Mock instance to get the actual mocked object.

var x = new FirstClass(mock.Object);

Mock class is used for settings up methods / verifications. You need to use Object accessor due to C# compiler restriction. You can vote for having it lifted on Microsoft Connect (see a note in QuickStart).

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126