Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Moq mock-objects to constructor

Tags:

c#

.net

mocking

moq

I've been using RhinoMocks for a good while, but just started looking into Moq. I have this very basic problem, and it surprises me that this doesn't fly right out of the box. Assume I have the following class definition:

public class Foo {     private IBar _bar;      public Foo(IBar bar)     {         _bar = bar;      }     .. } 

Now I have a test where I need to Mock the IBar that send to Foo. In RhinoMocks I would simply do it like follows, and it would work just great:

var mock = MockRepository.GenerateMock<IBar>();  var foo = new Foo(mock);  

However, in Moq this doesn't seem to work in the same way. I'm doing as follows:

var mock = new Mock<IBar>();  var foo = new Foo(mock);  

However, now it fails - telling me "Cannot convert from 'Moq.Mock' to 'IBar'. What am I doing wrong? What is the recommended way of doing this with Moq?

like image 752
stiank81 Avatar asked Aug 10 '11 13:08

stiank81


People also ask

Can we mock constructor using Mockito?

Starting with Mockito version 3.5. 0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes.

Can you mock a class 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. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.

What can be mocked with Moq?

Unit testing is a powerful way to ensure that your code works as intended. It's a great way to combat the common “works on my machine” problem. Using Moq, you can mock out dependencies and make sure that you are testing the code in isolation.

What is Mockbehavior strict?

Strict the mock behaves just like the object of the class you've mocked. It causes the mock to always throw an exception for invocations that don't have a corresponding expectation. Thus, if the you slightly changed the class (added a method), you'll also want to add that method to the mock to make your tests pass.


1 Answers

You need to pass through the object instance of the mock

var mock = new Mock<IBar>();   var foo = new Foo(mock.Object); 

You can also use the the mock object to access the methods of the instance.

mock.Object.GetFoo(); 

moq docs

like image 155
skyfoot Avatar answered Sep 21 '22 21:09

skyfoot