Reputation: 72
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;
}
Upvotes: 1
Views: 481
Reputation: 3880
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.
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();
Upvotes: 4