How to mock and expect a method with Action delegate as one of the parameter with Moq - asp.net-core

I am using Automapper in my .net core application to map. I have a method like below
public MyEntity TransformtoToEntity(MyDTO dto)
{
var entity = _mapper.Map<MyEntity, MyDTO>(dto, opts => opts.Items["isUpdate"] = "N");
return entity;
}
My test method looks like
[Fact]
public void Returns_Data_After_Mapping()
{
// Arrange
var mockEntityData = new MyEntity
{
Id = 1,
Name = "John"
};
var mockDto = new MyDTO
{
Id = 1,
Name = "John"
};
var mappingOperationMock = new Mock<IMappingOperationOptions<MyDTO, MyEntity>>(MockBehavior.Strict);
mappingOperationMock.Setup(x => x.Items).Returns(new Dictionary<string, object>() { { "isUpdate", "N" }});
_mapper.Setup(x => x.Map(It.IsAny<MyDTO>(),
It.IsAny<Action<IMappingOperationOptions<MyDTO, MyEntity>>>()))
.Returns(mockEntityData);
// Act
var result = _myMapper.TransformDtoToEntity(mockDto);
// Assert
Assert.NotNull(result);
_mapper.VerifyAll();
mappingOperationMock.VerifyAll();
}
Here how can I verify that IMappingOperationOptions parameters are correctly passed. Or is there any better way to do a unit test here. Basically I am stuck with how to effectively unit test methods who are having Action delegate parameters. I referred the thread Testing a method accepting a delegate with Moq, but could not find anything I can assert or verify inside the callback.

If you would like to test what is happening in your action delegate you can use the callback from moq.
Something like
Action<IMappingOperationOptions<MyEntity, MyDto>> mappingOperationAction = default;
_mapper.setup(x.Map(myDto, It.IsAny<Action<IMappingOperationOptions<MyEntity,MyDto>>>())
.callBack<MyDto, Action<IMappingOperationOptions<MyEntity,MyDto>>>( (callbackMyDto, callbackMappingOperationAction) => mappingOperationAction = callbackMappingOperationAction);
var mappingOperation = new MappingOperationOptions<MyEntity, MyDto>(_ => default);
mappingOperationAction.Invoke(mappingOperation);
Assert.AreEqual("N", mappingOperation.Items["isUpdate"])

Related

Xunit Unit Testing for Dot Net core application

I recently started learning Unit Testing and now have the requirement write unit tests using Xunit and Moq for dot net core application.
I can write some very basic but when it comes to write them for complex classes , I am kind of stuck.
Below is the class I will be writing tests for.
public class AgeCategoryRequestHandler : IInventoryRequestHandler<InventoryRequest, HandlerResult>
{
private readonly IRepositoryResolver _repositoryResolver;
Hotels.HBSI.Logging.ILogger logger;
public AgeCategoryRequestHandler(IRepositoryResolver repositoryResolver, Hotels.HBSI.Logging.ILogger iLogger)
{
_repositoryResolver = repositoryResolver;
logger = iLogger;
}
public async Task<HandlerResult> Run(InventoryRequest inventoryRequest)
{
var result = await ProcessRequest(inventoryRequest);
return CreateResponse(inventoryRequest, result);
}
private async Task<int> ProcessRequest(InventoryRequest inventoryRequest)
{
logger.Info("AgeCategory requesthandler processrequest start");
var repository = _repositoryResolver.ResolveEstabAgeCategory();
if (repository is not null)
{
return await repository.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories)
.ConfigureAwait(false);
}
logger.Info("AgeCategory requesthandler processrequest complete");
return InernalError.reponotfound;
}
public HandlerResult CreateResponse(InventoryRequest inventoryRequest, int resultCount)
{
var requestCount = inventoryRequest.EstabAgeCategories.Count;
var handlerResult = new HandlerResult() { Id = RequestHandlerEnum.AgeCategrory.ToInt() };
if (requestCount > 0 && resultCount < requestCount)
{
handlerResult.IsSuccess = false;
handlerResult.ErrorCode = OTAErrorType.InvalidAgeCategory.ToInt();
}
else if (requestCount > 0 || requestCount == resultCount)
{
handlerResult.IsSuccess = true;
handlerResult.ErrorCode = 0;
}
return handlerResult;
}
}
Just to start , IRepositoryResolver and ILogger are in the constructor so I have created mock for these but unable to go beyond that as I am still in initial phase of learning.
Could someone explain me the steps/approach to accomplish this?.
Edit : What I have done so far is below ( can't figure out what are the things to be done and where to start or write )
Edit 2 : Did some more modifications to my test code , can someone comment if I am in right direction ? what else can I test ?
public class AgeCategoryRequestHandlerTest
{
private AgeCategoryRequestHandler _ageCategoryRequestHandler;
private readonly Mock<AgeCategoryRequestHandler> _ageCategory = new Mock<AgeCategoryRequestHandler>();
private readonly Mock<Hotels.HBSI.Logging.ILogger> _mockLogger = new Mock<Hotels.HBSI.Logging.ILogger>();
private readonly Mock<IRepositoryResolver> _mockRepositoryResolver = new Mock<IRepositoryResolver>();
public AgeCategoryRequestHandlerTest()
{
_ageCategoryRequestHandler = new AgeCategoryRequestHandler(_mockRepositoryResolver.Object, _mockLogger.Object);
}
[Fact]
public async void Testtt()
{
var fixture = new Fixture();
var inventory = fixture.Create<InventoryRequest>();
var hndlr = fixture.Create<HandlerResult>();
hndlr.ErrorCode = 0;
int resultCount = 3;
await _ageCategoryRequestHandler.Run(inventory);
HandlerResult response = _ageCategoryRequestHandler.CreateResponse(inventory, resultCount);
Assert.Equal(hndlr.ErrorCode, response.ErrorCode);
}
Tried running Chris B suggested code , was getting type conversion error EstabAgeCategories = new List<int>
Now I have used fixture for creating automatic objects and did some assert values. Below is the code sample
var fixture = new Fixture();
var inventoryRequest = fixture.Create<InventoryRequest>();
_mockRepository
.Setup(x => x.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories))
.ReturnsAsync(6);
_mockRepositoryResolver
.Setup(x => x.ResolveEstabAgeCategory())
.Returns(_mockRepository.Object);
// act
var result = await _ageCategoryRequestHandler.Run(inventoryRequest);
// assert
_mockRepository
.Verify(x => x.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories), Times.Once);
Assert.True(result.Id == 6);
Assert.True(result.ErrorCode == 0);
Assert.True(result.IsSuccess);
From the unit test code you've posted, it looks like you are getting confused on what to test.
Look at your class and identify your "public" interface i.e. what methods can be called from other parts of your code. You should really only test public methods. Private methods are usually tested via public methods.
Looking at AgeCategoryRequestHandler, you have two public methods - Run and CreateResponse. I would question whether CreateResponse needs to be public but we'll leave it for now. For each of these methods, you want to be asserting that the returned value is what you expect given the input value.
private AgeCategoryRequestHandler _ageCategoryRequestHandler;
// Not needed
private readonly Mock<AgeCategoryRequestHandler> _ageCategory = new Mock<AgeCategoryRequestHandler>();
private readonly Mock<Hotels.HBSI.Logging.ILogger> _mockLogger = new Mock<Hotels.HBSI.Logging.ILogger>();
private readonly Mock<IRepositoryResolver> _mockRepositoryResolver = new Mock<IRepositoryResolver>();
public AgeCategoryRequestHandlerTest()
{
_ageCategoryRequestHandler = new AgeCategoryRequestHandler(_mockRepositoryResolver.Object, _mockLogger.Object);
}
The set up of the unit test is going the right way - you have created mocks for your dependencies but I see you have created a mock for the class you are trying to test - this is not needed and can be removed. You want to be testing the actual class itself which you are initializing in the constructor.
public async Task<HandlerResult> Run(InventoryRequest inventoryRequest)
{
var result = await ProcessRequest(inventoryRequest);
return CreateResponse(inventoryRequest, result);
}
private async Task<int> ProcessRequest(InventoryRequest inventoryRequest)
{
_logger.LogInformation("AgeCategory requesthandler processrequest start");
var repository = _repositoryResolver.ResolveEstabAgeCategory();
if (repository != null)
{
return await repository.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories).ConfigureAwait(false);
}
_logger.LogInformation("AgeCategory requesthandler processrequest complete");
return 0;
}
We can test the public Run method by looking at the method and seeing what it is going to do when executed. Firstly, it's going to call a private method ProcessRequest. Inside ProcessRequest, the IRepositoryResolver dependency is going to be used. This means we need to "set up" this dependency in our unit test to satisfy the if (repository != null) condition.
I assume the IRepositoryResolver returns another interface (?) - something like:
public interface IRepository
{
Task<int> InsertUpdateEstabAgeCategoryDetail(List<int> x);
}
So in your unit test, you need to create a mock for the repository being returned from IRepositoryResolver:
private readonly Mock<IRepository> _mockRepository = new Mock<IRepository>();
Then, you need to set up the mock IRepositoryResolver to return the mock repository above:
_mockRepositoryResolver
.Setup(x => x.ResolveEstabAgeCategory())
.Returns(_mockRepository.Object);
This is to satisfy the if (repository != null) condition.
_mockRepository
.Setup(x => x.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories))
.ReturnsAsync(6);
Next, you need to set up the InsertUpdateEstabAgeCategoryDetail() method on the mock repository to return a value. This value is being returned by ProcessRequest() and then used to call CreateResponse(inventoryRequest, result) as the result parameter.
if (requestCount > 0 && resultCount < requestCount)
{
handlerResult.IsSuccess = false;
handlerResult.ErrorCode = (int)OTAErrorType.InvalidAgeCategory;
}
else if (requestCount > 0 || requestCount == resultCount)
{
handlerResult.IsSuccess = true;
handlerResult.ErrorCode = 0;
}
Now you can look at the CreateResponse method and by setting different values for inventoryRequest.EstabAgeCategories and setting up the mock _mockRepository.Setup(x => x.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories)).ReturnsAsync(6); to return different values, you can satisfy the different paths through the if statement.
CreateResponse is returning an instance of HandlerResult which in turn is being returned by Task<HandlerResult> Run. This is the returned object you want to make assertions on.
One of the unit test cases might look like this (I have not tested it myself):
[Fact]
public async Task GivenInventoryRequest_WhenRun_ThenHandlerResultReturned()
{
// arrange
var inventoryRequest = new InventoryRequest
{
EstabAgeCategories = new List<int>
{
1, 2, 3, 4, 5
}
};
_mockRepository
.Setup(x => x.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories))
.ReturnsAsync(6);
_mockRepositoryResolver
.Setup(x => x.ResolveEstabAgeCategory())
.Returns(_mockRepository.Object);
// act
var result = await _ageCategoryRequestHandler.Run(inventoryRequest);
// assert
_mockRepository
.Verify(x => x.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories), Times.Once);
Assert.True(result.Id == 0);
Assert.True(result.ErrorCode == 0);
Assert.False(result.IsSuccess);
}

ASP.NET Core Resolve Controller and call Action by name

I have a generic catch all controller/action that receive files, parse the json content and find out the controller name and action name to be called from that.
Here my previous .NET Framework (old ASP) implementation which worked great:
public async Task<ActionResult> Run(PackingSlip packingSlip, IEnumerable<HttpPostedFileBase> files)
{
var controllerName = packingSlip.service_name;
var actionName = packingSlip.service_object;
// get the controller
var ctrlFactory = ControllerBuilder.Current.GetControllerFactory();
var ctrl = ctrlFactory.CreateController(this.Request.RequestContext, controllerName) as Controller;
var ctrlContext = new ControllerContext(this.Request.RequestContext, ctrl);
var ctrlDescAsync = new ReflectedAsyncControllerDescriptor(ctrl.GetType());
ctrl.ControllerContext = ctrlContext;
// get the action
var actionDesc = ctrlDescAsync.FindAction(ctrlContext, actionName);
// execute
ActionResult result;
if (actionDesc is AsyncActionDescriptor actionDescAsync)
result = await Task.Factory.FromAsync((asyncCallback, asyncState) => actionDescAsync.BeginExecute(ctrlContext, new Dictionary<string, object> { { "packingSlip", packingSlip }, { "files", files } }, asyncCallback, asyncState), asyncResult => actionDescAsync.EndExecute(asyncResult), null) as ActionResult;
else
result = actionDesc.Execute(ctrlContext, new Dictionary<string, object> { { "packingSlip", packingSlip }, { "files", files } }) as ActionResult;
// return the other action result as the current action result
return result;
}
Now with ASP.NET Core (or .NET 5), ControllerBuilder doesn't exist anymore and most of those things changed.
I tried to inject a IControllerFactory and use it, but can't find the proper way to use it to call an action knowing the "controllerName" and "actionName". It should also, like before, determine if it was an async action or not and act accordingly.
Found the answer by myself.
AspCore have an hidden barely documented extension method that registers controllers in the DI container: AddControllersAsServices.
services.AddMvc().AddControllersAsServices();
Then you can use IServiceProvider to resolve your controllers.

HttpParameterBinding without code coverage

OpenCover On Cake script does not detect coverage on my Owin.Testing usage applying HttpPArameterBiding to some ApiController action parameter.
I have Created a new type of my ApiController that as an action with my ParameterBindingAttribute that I called FromHeaderAttribute. After that I created my Owin Test Server and respective HttpClient and did the requests and the proper asserts to validate that the Binding is working properly. The tests pass with sucess.
This is my unit tests Cake Task
Task("UnitTests")
.IsDependentOn("Build")
.IsDependentOn("RestoreNugets")
.DoesForEach(GetFiles($"{testsPath}/**/*.csproj"), (file) =>
{
var openCoverSettings = new OpenCoverSettings
{
OldStyle = true,
MergeOutput = true,
Register = "user",
LogLevel = OpenCoverLogLevel.Verbose,
ArgumentCustomization = args => args.Append("-coverbytest:*.Tests.dll").Append("-mergebyhash")
}
.WithFilter("+[AppRootName.*]*");
var projectName = file.GetFilename().ToString().Replace(".csproj",string.Empty);
var dotNetTestSettings = new DotNetCoreTestSettings
{
Configuration = "Release",
DiagnosticOutput = true,
Verbosity = DotNetCoreVerbosity.Normal,
ArgumentCustomization = (args)=>
{
args.Append($"--logger \"trx;LogFileName={projectName}-TestsResults.trx\"");
args.Append("--filter \"TestCategory=Unit|Category=Unit\"");
return args;
}
};
OpenCover(context => context.DotNetCoreTest(file.FullPath, dotNetTestSettings), new FilePath($"CoverageResults.xml"), openCoverSettings);
})
.Finally(()=>
{
Information($"Copying test reports to ${outputDir}/TestsResults .... ");
CopyFiles($"{testsPath}/**/TestResults/*.trx",$"{outputDir}/TestsResults");
ReportGenerator($"*-CoverageResults.xml", $"{outputDir}/Reports");
});
this is my XUnit test:
[Fact]
[Trait("Category", "Unit")]
public async Task WhenHeadersArePresent_SettingsShouldBeSetted()
{
HttpConfiguration configuration = new HttpConfiguration();
var container = new SimpleInjector.Container();
Mock<IApiControllerValidation> mockValidationInterface = new Mock<IApiControllerValidation>();
ManualResetEvent resetEvent = new ManualResetEvent(false);
Settings settingsReceived = null;
mockValidationInterface.Setup((validator) => validator.Assert(It.IsAny<object>(), It.IsAny<object>(), It.IsAny<IDictionary<string, string>>(), It.IsAny<IHttpActionResult>()))
.Callback<object, object, IDictionary<string, string>, IHttpActionResult>((header, body, parameters, result) =>
{
settingsReceived = header as Settings;
resetEvent.Set();
});
container.RegisterInstance(mockValidationInterface.Object);
using (var server = TestServer.Create(app =>
{
configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
configuration.MapHttpAttributeRoutes();
app.Use((owinContext, nextHandler)=> nextHandler());
app.UseWebApi(configuration);
}))
{
var client = server.HttpClient;
client.DefaultRequestHeaders.Add("header1", new List<string>() { "headervalue1" } );
client.DefaultRequestHeaders.Add("header2", new List<string>() { "headervalue2" });
var result = await client.PostAsync<Payload>("optionalHeader", new Payload("value1"), new JsonMediaTypeFormatter());
Assert.Equal(HttpStatusCode.OK,result.StatusCode);
};
resetEvent.WaitOne();
Assert.NotNull(settingsReceived);
Assert.Equal("headervalue1", settingsReceived.Header1);
Assert.Equal("headervalue2", settingsReceived.Header2);
}
And this is my Api Action were I want to test the FromHEader attribute that I have implement.
[HttpPost]
[Route("optionalHeader",Name = "PostValidation")]
public IHttpActionResult OptionalHeaders([FromHeader]Settings settings, [FromBody]Payload payload)
{
var result = Ok();
validation.Assert(settings,payload, null, result);
return result;
}
I expect that the code coverage of the test detects the usage of This type but its not because the report is showing 0 code coverage on my type.
I figured out what was the problem, and it was not related to anything related to asp.net framework HttpParameterBinding component.
instead of execute the code cover like this:
OpenCover(context => context.DotNetCoreTest(file.FullPath, dotNetTestSettings), new FilePath($"CoverageResults.xml"), openCoverSettings);
I changed that to be like this:
OpenCover(tool => {
tool.XUnit2($"{testsPath}/**/**/**/**/{projectName}.dll",xUnit2Settings);
}, new FilePath("./OpenCoverCoverageResults.xml"),openCoverSettings);
Also the Build must be done with configuration in debug mode so the OpenCover can use the pdbs.
The only thing that I still dont like is the path to the dlls to be explicit by the number of levels that are explicit and I also did not want to copy the dlls because that will take more time.

ServiceStack MockRequestContext CustomAuthUserSession

I'm unit testing my API service and all is well using the MockRquestContext. The calls to this.GetSession() always returns an IAuthSession, but I have a custom AuthUserSession and as far as I can tell, there's no way to create an instance of my custom AuthUserSession and add it to the mock context. Is this possible?
var service = container.Resolve<AgencyCaseService>();
service.SetResolver(new BasicResolver(container));
var context = new MockRequestContext() { ResponseContentType = ContentType.Json };
//Something like this
MyCustomAuthSession session = new MyCustomAuthSession() { set some values}
context.AuthSession = session//this doesn't exist but it's the type of thing i need to do
service.RequestContext = context;
The Session isn't on the Request Context, it requires a mixture of ICacheClient, SessionFeature and HttpRequest cookies to create.
You can look at the implementation for the way to mock it inside a Service, which shows it first tries to resolve it in a Container:
private object userSession;
protected virtual TUserSession SessionAs<TUserSession>()
{
if (userSession == null)
{
userSession = TryResolve<TUserSession>(); //Easier to mock
if (userSession == null)
userSession = Cache.SessionAs<TUserSession>(Request, Response);
}
return (TUserSession)userSession;
}
So to mock it you could just do:
container.Register(new MyCustomAuthSession() { /* set some values*/ });

How can I modify the result of a method call on a mocked object before it is returned?

Given the following streamlined example, using RhinoMocks and MSpec:
[Subject(typeof (LocationController))]
public class when_creating_a_location_with_invalid_model : context_for_location_controller
{
static LocationModel model = new LocationModel();
static SelectList states = new SelectList(new Dictionary<string,string> {
{ "IN", "Indiana" }, { "NY", "New York" }
});
static ActionResult result;
Establish context = () =>
{
LocationModelBuilder.Stub(x =>
x.Build(Arg<LocationModel>.Is.Equal(model))).Return(model);
}
Because of = () => result = subject.Create(model);
It should_automatically_select_a_state = () => result.Model<LocationModel>()
.States.ShouldNotBeEmpty();
}
How can I modify the object contained in the model variable before it is returned from the stubbed call of LocationModelBuilder.Build()? I want to perform an assignment like model.States = states just before return on Build(). I tried playing with the Do() handler but I give up...
Try using WhenCalled(). The parameter to WhenCalled allows access to the mocked method's arguments and you can also set the return value.
.WhenCalled(m => {
Model model = (Model) m.Arguments[0];
model.States = ...;
});