MOQ Unit test Framework
Mocking is the ability to isolate code which will run in production with a test version so that external resource calls like database calls, web service calls can be mocked for easier unit testing.
Benefits of Mocking
- Execution of tests becomes faster with mocking objects
- Supports parallel development when the functionality is not yet developed or dependent on another team
- Isolates specific components from the actual testing components
MockBehaviour
- MockBehaviour.Strict - Using this type will throw an exception if the mocked method is not setup. All the methods of the mocked object need to be setup. There is a chance existing tests might fail if an object is strictly mocked.
- MockBehaviour.Loose - Using this type will not throw an exception if all methods are not set up and hence fewer lines of code in our unit tests.
- MockBehaviour.Default - By default, all mocked objects have a Default mock behaviour
Argument matching in mocked methods
- It.Is<string>(number => number.StartsWith(‘x’)).Returns(true)
- It.IsIn(“x”, “y”, “z”).Returns(true)
- It.IsInRange(“a”,”z”, Range.IsInclusive).Returns(true)
- It.IsRegex(“[a-z]”,RegexOptions.None).Returns(true)
Setup
_mockObject.Setup(x => x.Method(parameters)). Returns();
_mockObject.Setup(x => x.Method(parameters)). ReturnsAsync();
_mockObject.Setup(x => x.Method(parameters)). Returns(Task.FromResult<T> (response));
Exceptions
var exception = Record.ExceptionAsync( () => {call the method});
var exception = Assert.Throws<ExceptionType>( () => {call the method });
var exception = Assert.ThrowsAsync<ExceptionType>( () => {call the method });
Assert.NotNull(exception)
Assert.IsType<exceptiontype>(exception)
Assert.Single()
Assert.Equal()
Mocking IOptions -
IOptions<T> options = Options.Create(new <T> { });
Setup for methods with out parameters -
Bool isValid = true;
Mock.Setup(x => x.IsValid(It.IsAny<string>(), out IsValid);
Mocking Property
Mock.SetUp(x => x.LicenseKey). Returns(“EXPIRED”);
Tracking changes to MOQ properties
SetupProperty()
SetupAllProperties()
MOQ Verify
Mom.Verify(x => x.IsValid(paramter)) - o verify if a method was executed
Mom.Verify(x => x.IsValid(It.IsNotNull<string>()), “Error Message”); - To add custom failure message.
_mockObject.Verify(_ => _.Method(), Times.Once);
_mockObject.Verify(_ => _.Method(), Times. AtleastOnce);
_mockObject.Verify(_ => _.Method(), Times. Never);
Property verify
mock.VerifyGet(x => x.Property)
mock.VerifyGet(x => x.Property, Times.Once)
mock.VerifySet(x => x.ValidMode = It.IsAny<ValidationMode>());
Advanced -
Raising Events - Raise()
Setup.Returns()
.Raises()
SetupSequence() - To set different results for the same setup
To Setup protected methods -
Using Moq.Protected;
.Protected().Setup<>(method name, ItExpr.IsAny<>).Returns(true)
LINQ to Mocks - [Use this to Setup mocks]
IInterface mockobj = Mock.Of<IInterface>
(
x = >
x.Method().Setup == true
x.Property.Setup == “OK”
)
Mocking Controller Context (httpcontext) -
ControllerContext context = new ControllerContext();
context.HttpContext = new DefaultHttpContext();
context.HttpContext.Request.Headers.Add();
context.HttpContext.Request.Scheme = "https";
context.HttpContext.Request.Host = new HostString("localhost");
context.HttpContext.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("xxx.0.0.1");
return context;
Mocking HttpContext -
private readonly DefaultHttpContext _httpContext = new DefaultHttpContext();
private readonly Mock<IServiceProvider> _serviceProvideMock = new Mock<IServiceProvider>
_httpContext.RequestServices = _serviceProvideMock.Object;
_httpContext.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("xxx.0.0.1");
_httpContext.Request.ContentLength = 123;
_httpContext.Request.Method = "Get";
_httpContext.Request.Scheme = "http";
_httpContext.Request.Path = "/path";
_httpContext.Request.Host = HostString.FromUriComponent("localhost");
Initialize Controller context -
private ControllerContext _controllerContext;
var actionDescriptor = new ControllerActionDescriptor();
var routeData = new RouteData();
_controllerContext = new ControllerContext()
{ ActionDescriptor = actionDescriptor, HttpContext = httpContext, RouteData = routeData };
_controllerContext.ActionDescriptor.ControllerName = "Test";
_controllerContext.ActionDescriptor.ActionName = "Test";
private readonly DefaultHttpContext _httpContext = new DefaultHttpContext();
private readonly Mock<IServiceProvider> _serviceProvideMock = new Mock<IServiceProvider>
_httpContext.RequestServices = _serviceProvideMock.Object;
_httpContext.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("xxx.0.0.1");
_httpContext.Request.ContentLength = 123;
_httpContext.Request.Method = "Get";
_httpContext.Request.Scheme = "http";
_httpContext.Request.Path = "/path";
_httpContext.Request.Host = HostString.FromUriComponent("localhost");
Initialize Controller context -
private ControllerContext _controllerContext;
var actionDescriptor = new ControllerActionDescriptor();
var routeData = new RouteData();
_controllerContext = new ControllerContext()
{ ActionDescriptor = actionDescriptor, HttpContext = httpContext, RouteData = routeData };
_controllerContext.ActionDescriptor.ControllerName = "Test";
_controllerContext.ActionDescriptor.ActionName = "Test";
Comments
Post a Comment