简体   繁体   中英

How can I mock a simple method using Moq framework?

Let's say I've a simple method which checks whether the passed number is Even & returns a boolean value. I'm new to mocking & trying it out. How can I mock this method using Moq framework?

public bool isEven(int x)
        {
            bool result = (x % 2 == 0) ? true : false;
            return result;
        }

Let's assume that method is part of an interface:

public interface IMyInterface
{
   bool isEven(int x);
}

what you do to mock it is:

Mock<IMyInterface> myMock = new Mock<IMyInterface>();
myMock.Setup(x => x.isEven(It.Any<int>())).Returns(true);

What that means, it will setup the method in a way, that regardless to the value passed as argument, will return true.

You can then pass that Mock to other class / dependency like that:

var myNewObject = new Whateverclass(myMock.Object)

If your method lives in the concrete class, you can still do that but you need to mark your method as virtual . Rest of the process is exactly the same.

What Moq does underneath it creates an instance of its own class (like proxy) and put the return values for the members (methods, properties) that has been configured in setup methods.

EDIT:

Concrete example:

public class MyClass
{
   public virtual bool isEven(int x) {
     return (x % 2 == 0);
   }
}

what you do to mock it is:

Mock<MyClass> myMock = new Mock<MyClass>();
myMock.Setup(x => x.isEven(It.Any<int>())).Returns(true);

var myNewObject = new Whateverclass(myMock.Object)

And finally partial implementation:

public class MyClass
{
   public virtual bool isEven(int x) {
         return (x % 2 == 0);
       }
   public bool OtherMethod() {
       return !isEven();
   }
}

Mock<MyClass> myMock = new Mock<MyClass>();
myMock.CallBase = true;
myMock.Setup(x => x.isEven(It.Any<int>())).Returns(true);

var result = myMock.Object.OtherMethod();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM