Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing mocking objects with Moq when constructor has parameters

I have read this answer by Ragzitsu for the same question. I am still confused how to implement things though. Can somebody give me an example of an implementation.

I have the following classes:

class Fizz : IFizz { }  class Buzz : IBuzz {  }  class Bar : IBar {  }  class Foo : IFoo {     public Foo(IBar bar, IFizz fizz, IBuzz buzz)     {         //initialize etc.     }      //public methods } 

What is the practical way to get around the constructor here? I want to do something like

var foo = new Mock<IFoo>(); 

In other words how would the code look after the advice

The best thing to do would be right click on your class and choose Extract interface.

like image 903
happygilmore Avatar asked Dec 22 '13 09:12

happygilmore


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.

How do you mock a method in MOQ?

First, we instantiate the FakeDbArticleMock class and indicate which setup we want to use for this test. Then, it is necessary to instantiate the repository we want to test and inject the mock instance into it. Finally, we call the method we are testing and assert the results.

How do you create a object in MOQ?

Simpler mock objects, using MoqRight-click on the TestEngine project (the one we want to add Moq to). Select “Manage NuGet Packages…” In the NuGet tab, select “Browse” and search for “Moq” – the library we want to add. There are several add-on libraries that make it easier to use Moq in different types of programs.


1 Answers

You can create mock where constructor has param arguments, by referring MockBehavior, shown below

Mock<testClass>(MockBehavior.Strict, new object[] {"Hello"});  
like image 195
Ashraf Alam Avatar answered Sep 21 '22 17:09

Ashraf Alam