Skip to main content

MOQ .Net Mocking Framework Overview


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
  1. Execution of tests becomes faster with mocking objects
  2. Supports parallel development when the functionality is not yet developed or dependent on another team
  3. Isolates specific components from the actual testing components

MockBehaviour
  1. 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.
  2. 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.
  3. MockBehaviour.Default - By default, all mocked objects have a Default mock behaviour

Argument matching in mocked methods
  1. It.Is<string>(number => number.StartsWith(‘x’)).Returns(true)
  2. It.IsIn(“x”, “y”, “z”).Returns(true)
  3. It.IsInRange(“a”,”z”, Range.IsInclusive).Returns(true)
  4. 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";

Comments

Popular posts from this blog

How to clear Visual Studio Cache

How to clear visual studio cache Many times, during development you would face situations where project references are not loaded properly or you get missing/error DLL's. This is because the Component cache gets corrupted randomly and without any warnings. The first option that needs to be done is to clear component cache and restart Visual Studio since the Cache might be holding onto previous DLL versions. Here are the steps on how to clear Visual Studio Cache, Clearing Component Cache: Close all Visual Studio Instances running in your machine. Also, make sure devenv.exe is not running in the Task Manager Delete the Component cache directory - %USERPROFILE%\AppData\Local\Microsoft\VisualStudio\1x.0\ComponentModelCache Restart Visual Studio The above steps should fix the cache issue most of the times, but some times that is not enough and you need to perform the below steps as well. Clearing User's Temp Folder: Open the temp folder in this locatio n -  %USERPROFILE%\AppData\Loc...

How to dependency inject to static class

.Net core supports dependency injection. There are many ways that you can inject services like constructor injection, action method injection, property injection. But there will be scenarios where you need to inject dependency services to static classes. For example, injecting services to extension methods. First, create a static class with a one property IServiceProvider type public void ConfigureServices(IServiceCollection services) { services.AddScoped<ILoggerEntry, LoggerEntry>(); services.AddTransient<IMongoRepository, MongoRepository>(); } Second, configure your services in ConfigureServices() method in Startup.cs and define the lifetime of the service instance using either Transient, Scoped or Singleton types. public void ConfigureServices(IServiceCollection services) { services.AddScoped<ILoggerEntry, LoggerEntry>(); services.AddTransient<IMongoRepository, MongoRepository>(); } For the next step to configure the Static class provider proper...

Error NU1605 - Detected package downgrade. Reference the package directly from the project to select a different version.

Error NU1605 - Detected package downgrade This error occurs when a dependency package has a version higher than an existing package version in the project solution. Solution: Add the following in .csproj file < PackageReference > < NoWarn >$( NoWarn ); NU1605 </ NoWarn > </ PackageReference > Another way to do this is to right-click on the solution and  click  Properties . Click  Build  and under  Errors and warnings  add 1605 to the  SuppressWarnings  text box. You can also add multiple error codes that you want to suppress by adding each separated by a comma. P.S. The below screenshot is in VS2019 Mac Version