Unity PerRequestLifetimeManager UnitTest - unit-testing

I have following Unity configuration:
public static void RegisterTypes(IUnityContainer container)
{
...
container.RegisterType<IRootDatabaseContext, RootEntities>(new PerRequestLifetimeManager());
...
}
And everything works fine. But when I also want to test this method:
[TestMethod]
public void AssertUnityConfigAreValid()
{
using (var container = new UnityContainer())
{
UnityConfig.RegisterTypes(container);
foreach (var registration in container.Registrations)
{
container.Resolve(registration.RegisteredType, registration.Name);
}
}
}
And when I run this test I get an error:
InvalidOperationException - Operation is not valid due to the current state of the object.
How can I replace LifeTimeManager into Unit test from PerRequestLifetimeManager to another one?

I've just found the solution for this issue:
Just need to add following code before this line in test
UnityConfig.RegisterTypes(container);
var request = new HttpRequest("fake", "https://127.0.0.1", null);
var respons = new HttpResponse(new StringWriter());
var context = new HttpContext(request, respons);
HttpContext.Current = context;

Related

How to write unit test for ActionFilter when using Service Locator

I am planning to write an ActionFilter for business validation and in which some services will be resolved via Service Locator(I know this is not good practice and as far as possible i avoid Service Locator pattern, but for this case i want to use it).
OnActionExecuting method of the filter is something like this:
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
// get validator for input;
var validator = actionContext.HttpContext.RequestServices.GetService<IValidator<TypeOfInput>>();// i will ask another question for this line
if(!validator.IsValid(input))
{
//send errors
}
}
Is it possible to write unit test for above ActionFilterand how?
Here is an sample on how to create a mock (using XUnit and Moq framework) to verify that the IsValid method is called and where the mock returns an false.
using Dealz.Common.Web.Tests.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using System;
using Xunit;
namespace Dealz.Common.Web.Tests.ActionFilters
{
public class TestActionFilter
{
[Fact]
public void ActionFilterTest()
{
/****************
* Setup
****************/
// Create the userValidatorMock
var userValidatorMock = new Mock<IValidator<User>>();
userValidatorMock.Setup(validator => validator
// For any parameter passed to IsValid
.IsValid(It.IsAny<User>())
)
// return false when IsValid is called
.Returns(false)
// Make sure that `IsValid` is being called at least once or throw error
.Verifiable();
// If provider.GetService(typeof(IValidator<User>)) gets called,
// IValidator<User> mock will be returned
var serviceProviderMock = new Mock<IServiceProvider>();
serviceProviderMock.Setup(provider => provider.GetService(typeof(IValidator<User>)))
.Returns(userValidatorMock.Object);
// Mock the HttpContext to return a mockable
var httpContextMock = new Mock<HttpContext>();
httpContextMock.SetupGet(context => context.RequestServices)
.Returns(serviceProviderMock.Object);
var actionExecutingContext = HttpContextUtils.MockedActionExecutingContext(httpContextMock.Object, null);
/****************
* Act
****************/
var userValidator = new ValidationActionFilter<User>();
userValidator.OnActionExecuting(actionExecutingContext);
/****************
* Verify
****************/
// Make sure that IsValid is being called at least once, otherwise this throws an exception. This is a behavior test
userValidatorMock.Verify();
// TODO: Also Mock HttpContext.Response and return in it's Body proeprty a memory stream where
// your ActionFilter writes to and validate the input is what you desire.
}
}
class User
{
public string Username { get; set; }
}
class ValidationActionFilter<T> : IActionFilter where T : class, new()
{
public void OnActionExecuted(ActionExecutedContext context)
{
throw new NotImplementedException();
}
public void OnActionExecuting(ActionExecutingContext actionContext)
{
var type = typeof(IValidator<>).MakeGenericType(typeof(T));
var validator = (IValidator<T>)actionContext.HttpContext
.RequestServices.GetService<IValidator<T>>();
// Get your input somehow
T input = new T();
if (!validator.IsValid(input))
{
//send errors
actionContext.HttpContext.Response.WriteAsync("Error");
}
}
}
internal interface IValidator<T>
{
bool IsValid(T input);
}
}
HttpContextUtils.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Generic;
namespace Dealz.Common.Web.Tests.Utils
{
public class HttpContextUtils
{
public static ActionExecutingContext MockedActionExecutingContext(
HttpContext context,
IList<IFilterMetadata> filters,
IDictionary<string, object> actionArguments,
object controller
)
{
var actionContext = new ActionContext() { HttpContext = context };
return new ActionExecutingContext(actionContext, filters, actionArguments, controller);
}
public static ActionExecutingContext MockedActionExecutingContext(
HttpContext context,
object controller
)
{
return MockedActionExecutingContext(context, new List<IFilterMetadata>(), new Dictionary<string, object>(), controller);
}
}
}
As you can see, it's quite a mess, you need to create plenty of mocks to simulate different responses of the actuall classes, only to be able to test the ActionAttribute in isolation.
I like #Tseng's above answer but thought of giving one more answer as his answer covers more scenarios (like generics) and could be overwhelming for some users.
Here I have an action filter attribute which just checks the ModelState and short circuits(returns the response without the action being invoked) the request by setting the Result property on the context. Within the filter, I try to use the ServiceLocator pattern to get a logger to log some data(some might not like this but this is an example)
Filter
public class ValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<ValidationFilterAttribute>>();
logger.LogWarning("some message here");
context.Result = new JsonResult(new InvalidData() { Message = "some messgae here" })
{
StatusCode = 400
};
}
}
}
public class InvalidData
{
public string Message { get; set; }
}
Unit Test
[Fact]
public void ValidationFilterAttributeTest_ModelStateErrors_ResultInBadRequestResult()
{
// Arrange
var serviceProviderMock = new Mock<IServiceProvider>();
serviceProviderMock
.Setup(serviceProvider => serviceProvider.GetService(typeof(ILogger<ValidationFilterAttribute>)))
.Returns(Mock.Of<ILogger<ValidationFilterAttribute>>());
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = serviceProviderMock.Object;
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
var actionExecutingContext = new ActionExecutingContext(
actionContext,
filters: new List<IFilterMetadata>(), // for majority of scenarios you need not worry about populating this parameter
actionArguments: new Dictionary<string, object>(), // if the filter uses this data, add some data to this dictionary
controller: null); // since the filter being tested here does not use the data from this parameter, just provide null
var validationFilter = new ValidationFilterAttribute();
// Act
// Add an erorr into model state on purpose to make it invalid
actionContext.ModelState.AddModelError("Age", "Age cannot be below 18 years.");
validationFilter.OnActionExecuting(actionExecutingContext);
// Assert
var jsonResult = Assert.IsType<JsonResult>(actionExecutingContext.Result);
Assert.Equal(400, jsonResult.StatusCode);
var invalidData = Assert.IsType<InvalidData>(jsonResult.Value);
Assert.Equal("some messgae here", invalidData.Message);
}

I Don't Understand The Difference In These Unit Tests

I'm using Moq, xUnit and Prism 4. My unit test's objective is to fire an event and confirm that a property has changed in my view model to match the value from the event. This test, by the way, fails (Expected:5, Actual:0):
// Version One
[Fact]
public void Should_set_DayCount_on_DayCountChangedEvent()
{
var eaMock = new Mock<IEventAggregator>();
eaMock.SetupCurriculumEvents(); // see below
var vm = new CurriculumItemViewModel(eaMock.Object, _systemStatus.Object);
vm.Load(_newItem);
var dayCount = 5;
eaMock.Object.GetEvent<DayCountChangedNotification>().Publish(dayCount);
Assert.Equal(dayCount, _vm.DayCount);
}
I got tired of setting up my event aggregator mock everywhere, so I created an extension method to do the dirty work for me:
public static void SetupCurriculumEvents(this Mock<IEventAggregator> eaMock)
{
eaMock.Setup(ea => ea.GetEvent<DayCountChangedNotification>())
.Returns(new DayCountChangedNotification());
// lots of other "notification" events here as well
}
Then I realized that I'm creating a new event every time it's retrieved from the mock event aggregator, so the Subscribe() on one instance (in the VM) isn't on the same instance as the Publish(dayCount) in my test.
Well, methinks, let's just always use the same object (by overwriting the extension method's Setup() for this event) and we're gonna be good:
// Version Two
[Fact]
public void Should_set_DayCount_on_DayCountChangedEvent()
{
var dayCountChangedEvent = new DayCountChangedNotification();
var eaMock = new Mock<IEventAggregator>();
eaMock.SetupCurriculumEvents(); // still need this for all the other events
// overwrite the setup from the extension method
eaMock.Setup(ea => ea.GetEvent<DayCountChangedNotification>())
.Returns(dayCountChangedEvent);
var vm = new CurriculumItemViewModel(eaMock.Object, _systemStatus.Object);
vm.Load(_newItem);
var dayCount = 5;
dayCountChangedEvent.Publish(dayCount);
Assert.Equal(dayCount, _vm.DayCount);
}
... which also fails spectacularly.
For some reason, I decided to try refactoring the extension method, (and reverted the unit test back to Version One):
public static class MockingExtensions
{
private static DayCountChangedNotification DayNotification = new DayCountChangedNotification();
public static void SetupCurriculumEvents(this Mock<IEventAggregator> eaMock)
{
eaMock.Setup(ea => ea.GetEvent<DayCountChangedNotification>())
.Returns(DayNotification);
// etc...
}
}
... which to my mind, is basically the same thing - I'm always returning the same instance of the Event.
Here's the kicker: this test passes.
That's great and everything, but I don't understand why it passes - and if I don't understand why it's passing, then I don't really know if it's right or not.
Accepted answer needs to explain two things:
Why does the refactored extension method with the static instance pass?
Why doesn't Version Two pass?
I tried to reproduce your problem and created the code below. All three tests succeeded so i think something is missing in the question. It is important to know that moqObject.Setup(...).Return(true) is not the same as moqObject.Setup(...).Return(() => true). See for more info here
namespace Test
{
using Microsoft.Practices.Prism.Events;
using Moq;
using System;
using Xunit;
// Moq 4.2.1510.2205
// Prism 4.0.0.0
// xunit 2.1.0
public class CurriculumItemViewModel
{
public CurriculumItemViewModel(IEventAggregator agg)
{
agg.GetEvent<DayCountChangedNotification>().Subscribe((int? x) => {
DayCount = x.Value;
});
}
public int DayCount { get; set; }
}
public class DayCountChangedNotification : CompositePresentationEvent<int?>
{
public DateTime Created = DateTime.Now;
}
public static class Extensions
{
private static DayCountChangedNotification DayNotification = new DayCountChangedNotification();
public static void SetupCurriculumEventsV1(this Mock<IEventAggregator> eaMock)
{
eaMock.Setup(ea => ea.GetEvent<DayCountChangedNotification>())
.Returns(new DayCountChangedNotification());
}
public static void SetupCurriculumEventsV2(this Mock<IEventAggregator> eaMock)
{
eaMock.Setup(ea => ea.GetEvent<DayCountChangedNotification>())
.Returns(DayNotification);
}
}
public class TestClass
{
[Fact]
public void ShouldSetDayCountOnDayCountChangedEvent1a()
{
// Arrange
var dayCount = 5;
var eaMock = new Mock<IEventAggregator>();
eaMock.SetupCurriculumEventsV1();
var vm = new CurriculumItemViewModel(eaMock.Object);
var notification = eaMock.Object.GetEvent<DayCountChangedNotification>();
var notification2 = eaMock.Object.GetEvent<DayCountChangedNotification>();
// Act
notification.Publish(dayCount);
// Assert
Assert.Equal(dayCount, vm.DayCount);
}
[Fact]
public void ShouldSetDayCountOnDayCountChangedEvent2()
{
// Arrange
var dayCount = 5;
var eaMock = new Mock<IEventAggregator>();
eaMock.SetupCurriculumEventsV1();
// This will override the setup done by SetupCurriculumEventsV1
var notification = new DayCountChangedNotification();
eaMock.Setup(ea => ea.GetEvent<DayCountChangedNotification>())
.Returns(notification);
var vm = new CurriculumItemViewModel(eaMock.Object);
// Act
notification.Publish(dayCount);
// Assert
Assert.Equal(dayCount, vm.DayCount);
}
[Fact]
public void ShouldSetDayCountOnDayCountChangedEvent1b()
{
// Arrange
var dayCount = 5;
var eaMock = new Mock<IEventAggregator>();
eaMock.SetupCurriculumEventsV2();
var vm = new CurriculumItemViewModel(eaMock.Object);
var notification = eaMock.Object.GetEvent<DayCountChangedNotification>();
// Act
notification.Publish(dayCount);
// Assert
Assert.Equal(dayCount, vm.DayCount);
}
}
}

How to unit test Service Stacks Redis Client with Moq

I'm trying to understand how can I mock the IRedisClientsManager so that I can unit test the Handle Method below using Moq.
Cheers
public class PropertyCommandHandler : ICommandHandlerFor<PropertySaveRequest, PropertyCommandResult>
{
private readonly IRedisClientsManager _manager;
public PropertyCommandHandler(IRedisClientsManager manager)
{
this._manager = manager;
}
public PropertyCommandResult Handle(PropertySaveRequest request)
{
request.Property.OwnerId.ValidateArgumentRange();
using (var client =_manager.GetClient())
{
var propertyClient = client.As<Model.Property>();
var propertyKey = string.Format("property:{0}", request.Property.OwnerId);
propertyClient.SetEntry(propertyKey, request.Property);
client.AddItemToSet("property", request.Property.OwnerId.ToString());
}
return new PropertyCommandResult() {Success = true};
}
}
Which I call from the service like so
public class PropertyService : Service, IPropertyService
{
private readonly ICommandHandlerFor<PropertySaveRequest, PropertyCommandResult> _commandHandler;
public PropertyService(ICommandHandlerFor<PropertySaveRequest, PropertyCommandResult> commandHandler)
{
this._commandHandler = commandHandler;
}
public object Post(PropertySaveRequest request)
{
if (request.Property == null)
throw new HttpError(HttpStatusCode.BadRequest, "Property cannot be null");
var command = _commandHandler.Handle(request);
return command;
}
}
so far this has been the approach - not sure if on right track
[Test]
public void TestMethod1()
{
//arrange
_container = new WindsorContainer()
.Install(new PropertyInstaller());
var mock = new Mock<IRedisClientsManager>();
var instance = new Mock<RedisClient>();
mock.Setup(t => t.GetClient()).Returns(instance);
// cannot resolve method error on instance
// stuck ...
var service = _container.Resolve<IPropertyService>(mock);
}
In short, since RedisClient implements IRedisClient, did you try to create the mock using the interface?
var instance = new Mock<IRedisClient>();
why are you using a real container for your unit test?
You should use an auto-mocking container or simply (since you are already taking care of the mock manually) create a real instance of your test target supplying mocks as dependencies
var target= new PropertyCommandHandler(mock);
BTW IMHO a "command handler" that returns a value sounds like a smell...

Moq Error : Moq.MockVerificationException: The following setups were not matched

I wanna test my method with mock but it throw this exception. My class is this (this class do some simple actions on a file as though unzipping the file) :
public class FileActions
{
public virtual void Decompress(FileInfo fileInfo, DirectoryInfo directoryInfo)
{
ZipFile.ExtractToDirectory(fileInfo.FullName, directoryInfo.FullName);
}
public virtual FileInfo GetConvertedFileToZip(FileInfo fileInfo)
{
try
{
var changeExtension = Path.ChangeExtension(fileInfo.FullName, "zip");
File.Move(fileInfo.FullName, changeExtension);
return new FileInfo(changeExtension);
}
catch (Exception)
{
throw new FileNotFoundException();
}
}
}
and this is my test :
public void TestMockedMethodForNotNull()
{
var mock = new Mock<FileActions>();
var fInfo = new FileInfo(#"D:\ZipFiles\elmah.nupkg");
mock.Setup(s => s.GetConvertedFileToZip(fInfo)).Verifiable();
mock.VerifyAll();
}
So, why does it get this Error :
Moq.MockVerificationException: The following setups were not matched:
FileActions2 s => s.GetConvertedFileToZip(D:\ZipFiles\elmah.nupkg)
There are several issues with your Unit Test. I will only highlight the mocking side of things, as it relevant to the question you ask. Also your question has refer to "FileActions2", and I think this
a mistake when you originally add the question.
You Test:
[TestMethod]
public void TestMockedMethodForNotNull()
{
var mock = new Mock<FileActions>();
var fileInfo = new FileInfo(#"D:\ZipFiles\elmah.nupkg");
mock.Setup(s => s.GetConvertedFileToZip(fileInfo)).Verifiable();
mock.VerifyAll();
}
The way you have written this test, Moq won't verify on GetConvertedFileToZip
This test fail fundamentally because Moq cannot provide an override for a virtual method GetConvertedFileToZip. You must create a proxy i,e mock.Object.
If you modify your test in such a way so your SUT (Sysytem Under Test), consumes an instance of the mocked object/proxied object
your verify would work partially (partially means you are heading right direction). Still something else to fix which I have described below.
Assuming your SUT is like below
public class Sut
{
public void Do(FileActions fileActions)
{
var fileInfo = new FileInfo(#"D:\ZipFiles\elmah.nupkg");
var s = fileActions.GetConvertedFileToZip(fileInfo);
}
}
Your Test
[TestMethod]
public void TestMockedMethodForNotNull()
{
var mock = new Mock<FileActions>();
var fileInfo = new FileInfo(#"D:\ZipFiles\elmah.nupkg");
mock.Setup(s => s.GetConvertedFileToZip(fileInfo)).Verifiable();
var sut = new Sut();
sut.Do(mock.Object);
mock.VerifyAll();
}
This would produce an exception. This is because fileInfo you have setup on does not match the verification, when invoke via the Sut.
If you were to modify this test as below, this would succeed
[TestMethod]
public void TestMockedMethodForNotNull()
{
var mock = new Mock<FileActions>();
//var fileInfo = new FileInfo(#"D:\ZipFiles\elmah.nupkg");
mock.Setup(s => s.GetConvertedFileToZip(It.IsAny<FileInfo>())).Verifiable();
var sut = new Sut();
sut.Do(mock.Object);
mock.VerifyAll();
}

How to reset autofac container?

In my tests I setup an autofac container, it returns some real implementation and some mocks (DB, external systems).
The problem is that after each test I Dispose the container and create a new one:
Autofac.IContainer.Dispose() and Container = builder.Build();
The already registered instances are still there.
How can I reset the container so it would be 'like new' again?
The reason why I want to do is - I want to replace one mocked instance with another. It's being registered as Singleton.
---- EDIT
Thanks for the answers. I decided to add some more code and describe what actually I'm trying to achieve. But that is actually a topic for another (prabably already answered question - unit testing CQRS).
My app contains static IContainer property:
public static IContainer Container { get; private set; }
After each test execution I create it again by calling those two methods:
public static ContainerBuilder Compose(IEnumerable<DependencyProvider> dependencyProviders)
{
var collection = dependencyProviders as List<DependencyProvider> ?? dependencyProviders.ToList();
var included = new HashSet<DependencyProvider>(collection);
var includedTypes = new HashSet<Type>(collection.Select(x => x.GetType()));
var currentWorkingSet = new List<DependencyProvider>(collection);
while (true)
{
var candidates = currentWorkingSet.SelectMany(x => x.GetDependencies());
var typesToBeAdded = candidates.Where(x => !includedTypes.Contains(x)).Distinct().ToList();
if (typesToBeAdded.Any() == false)
break;
currentWorkingSet.Clear();
foreach (var type in typesToBeAdded)
{
includedTypes.Add(type);
var instance = CreateInstance(type);
included.Add(instance);
currentWorkingSet.Add(instance);
}
}
return BuildContainer(included);
}
and
TestDependencyProvider dependencyProvider = new TestDependencyProvider()
var builder = Compose(new[] { dependencyProvider });
Container = builder.Build();
The TestDependencyProvider is created for each test and contains moqed instances. It registers those mocks and x.GetDependencies() uses the original container registrations i.e. container.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsClosedTypesOf(typeof(IAggregateBusinessRuleForEvent<,>));
The type I'm mostly interested in is one of implementations of IAggregateBusinessRuleForEvent<,>).
public class RuleA: IAggregateBusinessRuleForEvent<AEvent, Something>
{
private readonly IDependency _dependency;
public RejectCompanyNameRule(IDependency dependency)
{
_dependency = dependency;
}
}
So even though I create this container again that RuleA is still there and all of my test are using same instance with same _dependency :/
It's still not entierly clear why code looks how it looks, I'm trying to understand it by adding tests...
------- EDIT 2
Following Jimmy's advice I've implemented a sample using Update me
public interface IExample<T>
{
void Hello();
}
public interface IExampleDependecy
{
void SaySomething();
}
public class Example : IExample<string>
{
private IExampleDependecy _dependecy;
public Example(IExampleDependecy dependecy)
{
_dependecy = dependecy;
}
public void Hello()
{
Console.WriteLine("Hello");
_dependecy.SaySomething();
}
}
[TestMethod]
public void T()
{
// first test
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsClosedTypesOf(typeof(IExample<>));
var mockA = new Moq.Mock<IExampleDependecy>();
mockA.Setup(d => d.SaySomething()).Callback(() => Console.WriteLine("A"));
builder.RegisterInstance(mockA.Object).SingleInstance();
var container = builder.Build();
var sample1 = container.Resolve<IExample<string>>();
sample1.Hello();
// new test using same container
var updater = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsClosedTypesOf(typeof(IExample<>));
var mockB = new Moq.Mock<IExampleDependecy>();
mockB.Setup(d => d.SaySomething()).Callback(() => Console.WriteLine("B"));
builder.RegisterInstance(mockB.Object).SingleInstance();
updater.Update(container); // overwrites existing registrations
var sample2 = container.Resolve<IExample<string>>();
sample2.Hello();
}
and result is:
Hello
A
Hello
A
Autofac by default overrides previous registrations with subsequent ones. That means you don't have to do anything special apart from updating container with your new instance:
var builder = new ContainerBuilder();
builder.RegisterInstance(new Sample("A")).SingleInstance();
var container = builder.Build();
var sample = container.Resolve<Sample>();
// do your test
...
// new test using same container
var updater = new ContainerBuilder();
updater.RegisterInstance(new Sample("B")).SingleInstance();
updater.Update(container); // overwrites existing registrations
var sample = container.Resolve<Sample>(); // returns "B"