How can I provide implementation of methods using Moq?

I have an interface with several methods. I have a default implementation of this interface. For the purpose of integration tests, I would like to create a mock implementation that returns my custom value if one of these methods is called, and otherwise returns to the default implementation. Is this possible with Moq, or should I create a simple stub?

Example

IInterface default = new DefaultImplementation(); var mock = new Mock<IInterface>(); mock.Setup(i => i.Method(It.IsAny<>())).Calls(p => p==0 ? return 5 : default.Method(p);); TheMethodITest(mock.Object()); //if it calls the object with 0 then it should get 5, otherwise it should call the default object 
+6
source share
2 answers

I am not sure what is the condition for providing a default value or your specific value. However, it looks like you want to customize the layout with Delegator .

 public void MoqCanBeSetupWithDelegator() { var mock = new Mock<IInterface>(); Func<string, int> valueFunction = i => i == "true" ? 1 : default(int); mock.Setup(x => x.Method(It.IsAny<string>())).Returns(valueFunction); Assert.Equal(1, mock.Object.Method("true")); Assert.Equal(0, mock.Object.Method("anonymous")); } public interface IInterface { int Method(string arg); } 

As you can see, the Returns method is overloaded to accept a return value ( int ) or a delegate representing a fake method signature. You can use Func<string, int> to replace the actual implementation - int Method(string arg) .

+5
source

You can do this by installing Mock in a specific class and using As() to retrieve the base IInterface on which to configure. Then you can use mock.Object to call the base specific object:

  [Test] public void SomeTest() { var mock = new Mock<DefaultImplementation>().As<IInterface>(); mock.Setup(i => i.Method(It.IsAny<int>())) .Returns<int>(p => p == 0 ? 5 : ((DefaultImplementation)mock.Object).Method(p)); TheMethodITest(mock.Object); } 

Here are the rest of the settings I tested with, FWIW:

 public interface IInterface { int Method(int p); } public class DefaultImplementation : IInterface { public int Method(int p) { return 6; } } [TestFixture] public class SomeFixture { public static void TheMethodITest(IInterface dep) { for (var i = 0; i < 10; i++) { Debug.WriteLine("{0}:{1}",i, dep.Method(i)); } } } 
+2
source

Source: https://habr.com/ru/post/970703/


All Articles