Moq how to do a setup when the item could be any of a type but must have a particular property set - moq

I'm trying to setup for a method which will run:
dataAccess.Setup(x => x.GetCars(It.IsAny<CarFilter>()));
Ok, so I'm saying to setup the method GetCars when it is passed any object of type CarFilter.
I want to make this a little more specific.
I want to make it so it will setup when it is passed any object of type CarFilter when the property on CarFilter Color = "Red".
Does anybody know how to write this?

You can put a condition on the match using It.Is(...)
public class Car {
public string Color { get; set; }
}
public interface IFoo {
void DoIt(Car car);
}
[TestMethod]
public void PassesWhenRed() {
var mockFoo = new Mock<IFoo>();
var redCar = new Car { Color = "Red" };
mockFoo.Object.DoIt(redCar);
mockFoo.Verify(mk=>mk.DoIt(It.Is<Car>(car => car.Color == "Red"))); // Passes
}
[TestMethod]
public void FailsWhenNotRed() {
var mockFoo = new Mock<IFoo>();
var blueCar = new Car { Color = "Blue" };
mockFoo.Object.DoIt(blueCar);
mockFoo.Verify(mk=>mk.DoIt(It.Is<Car>(car => car.Color == "Red"))); // Fails
}

Ended up needing:
dataAccess.Setup(x => x.GetCars(It.Is<CarFilter>(z => z.Color == "Red")));

Related

Extending existing ABP controllers

I am using version 3.3.2 of the ABP Framework. How can I add new methods to an existing controller? I want to extend the IdentityUserController. Following the docs I am creating my own implementation as following:
[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(IdentityUserController))]
public class MyIdentityUserController : IdentityUserController
{
public MyIdentityUserController(IIdentityUserAppService userAppService) : base(userAppService)
{
}
public override Task<PagedResultDto<IdentityUserDto>> GetListAsync(GetIdentityUsersInput input)
{
return base.GetListAsync(input);
}
[HttpGet]
[Route("my-method")]
public Task<string> MyMethod()
{
return Task.FromResult("Works");
}
}
The overrides actually work but my custom method is not visible in Swagger and when I try to access it with Postman it is not accessible either. Any ideas how I can extend existing controllers? I don't want to create a whole new controller since I have a combination with overrides and new methods. I would like to keep everything together.
First, set IncludeSelf = true — we will use this to determine whether to replace the existing controller with the extended controller, and ASP.NET Core will resolve your controller by class.
Optionally, add [ControllerName("User")] from IdentityUserController since it is not inherited:
[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(IdentityUserController), IncludeSelf = true)]
[ControllerName("User")]
public class MyIdentityUserController : IdentityUserController
Option 1
Subclass AbpServiceConvention and override RemoveDuplicateControllers to remove the existing controller(s) instead of your extended controller:
var exposeServicesAttr = ReflectionHelper.GetSingleAttributeOrDefault<ExposeServicesAttribute>(controllerModel.ControllerType);
if (exposeServicesAttr.IncludeSelf)
{
var existingControllerModels = application.Controllers
.Where(cm => exposeServicesAttr.ServiceTypes.Contains(cm.ControllerType))
.ToArray();
derivedControllerModels.AddRange(existingControllerModels);
Logger.LogInformation($"Removing the controller{(existingControllerModels.Length > 1 ? "s" : "")} {exposeServicesAttr.ServiceTypes.Select(c => c.AssemblyQualifiedName).JoinAsString(", ")} from the application model since {(existingControllerModels.Length > 1 ? "they are" : "it is")} replaced by the controller: {controllerModel.ControllerType.AssemblyQualifiedName}");
continue;
}
Full code of subclass:
public class MyAbpServiceConvention : AbpServiceConvention
{
public MyAbpServiceConvention(
IOptions<AbpAspNetCoreMvcOptions> options,
IConventionalRouteBuilder conventionalRouteBuilder)
: base(options, conventionalRouteBuilder)
{
}
protected override void RemoveDuplicateControllers(ApplicationModel application)
{
var derivedControllerModels = new List<ControllerModel>();
foreach (var controllerModel in application.Controllers)
{
if (!controllerModel.ControllerType.IsDefined(typeof(ExposeServicesAttribute), false))
{
continue;
}
if (Options.IgnoredControllersOnModelExclusion.Contains(controllerModel.ControllerType))
{
continue;
}
var exposeServicesAttr = ReflectionHelper.GetSingleAttributeOrDefault<ExposeServicesAttribute>(controllerModel.ControllerType);
if (exposeServicesAttr.IncludeSelf)
{
var existingControllerModels = application.Controllers
.Where(cm => exposeServicesAttr.ServiceTypes.Contains(cm.ControllerType))
.ToArray();
derivedControllerModels.AddRange(existingControllerModels);
Logger.LogInformation($"Removing the controller{(existingControllerModels.Length > 1 ? "s" : "")} {exposeServicesAttr.ServiceTypes.Select(c => c.AssemblyQualifiedName).JoinAsString(", ")} from the application model since {(existingControllerModels.Length > 1 ? "they are" : "it is")} replaced by the controller: {controllerModel.ControllerType.AssemblyQualifiedName}");
continue;
}
var baseControllerTypes = controllerModel.ControllerType
.GetBaseClasses(typeof(Controller), includeObject: false)
.Where(t => !t.IsAbstract)
.ToArray();
if (baseControllerTypes.Length > 0)
{
derivedControllerModels.Add(controllerModel);
Logger.LogInformation($"Removing the controller {controllerModel.ControllerType.AssemblyQualifiedName} from the application model since it replaces the controller(s): {baseControllerTypes.Select(c => c.AssemblyQualifiedName).JoinAsString(", ")}");
}
}
application.Controllers.RemoveAll(derivedControllerModels);
}
}
Option 2
Implement IApplicationModelConvention to add your extended controller to IgnoredControllersOnModelExclusion and remove the existing controller:
public class ExtendedControllerApplicationModelConvention : IApplicationModelConvention
{
private readonly Lazy<IOptions<AbpAspNetCoreMvcOptions>> _lazyOptions;
public ExtendedControllerApplicationModelConvention (IServiceCollection services)
{
_lazyOptions = services.GetRequiredServiceLazy<IOptions<AbpAspNetCoreMvcOptions>>();
}
public void Apply(ApplicationModel application)
{
var controllerModelsToRemove = new List<ControllerModel>();
var ignoredControllersOnModelExclusion = _lazyOptions.Value.Value.IgnoredControllersOnModelExclusion;
foreach (var controllerModel in application.Controllers)
{
var exposeServicesAttr = ReflectionHelper.GetSingleAttributeOrDefault<ExposeServicesAttribute>(controllerModel.ControllerType);
if (exposeServicesAttr != null && exposeServicesAttr.IncludeSelf)
{
ignoredControllersOnModelExclusion.AddIfNotContains(controllerModel.ControllerType);
var existingControllerModels = application.Controllers
.Where(cm => exposeServicesAttr.ServiceTypes.Contains(cm.ControllerType));
controllerModelsToRemove.AddIfNotContains(existingControllerModels);
}
}
application.Controllers.RemoveAll(controllerModelsToRemove);
}
}
In your module, insert ExtendedServiceApplicationModelConvention before AbpServiceConventionWrapper:
public override void ConfigureServices(ServiceConfigurationContext context)
{
// ...
Configure<MvcOptions>(options =>
{
var abpServiceConvention = options.Conventions.OfType<AbpServiceConventionWrapper>().First();
options.Conventions.InsertBefore(abpServiceConvention, new ExtendedControllerApplicationModelConvention (context.Services));
});
}
I created a test project using the same version of ABP v3.3.2 and managed to get this working.
You can override the original methods in a new class that inherits from the original IdentityUserController, but you need to create your own controller to 'add' new methods to it. If you create a new controller that includes the same class attributes as IdentityUserController then it will appear like it has been extended.
[RemoteService(Name = IdentityRemoteServiceConsts.RemoteServiceName)]
[Area("identity")]
[ControllerName("User")]
[Route("api/identity/users")]
[ExposeServices(typeof(MyIdentityUserController))]
public class MyIdentityUserController : AbpController, IApplicationService, IRemoteService
{
[HttpGet("my-method")]
public Task<string> MyMethod()
{
return Task.FromResult("Works");
}
}

UNITY v.3 - BehaviorInterception using namespace matching

How can I apply a behavior to all interface in a specific namespace?
I know how to apply a behavior to a concrete interface like IMyBlFacade,
but I don't want to do that for all interfaces separately, but in one shot.
Is implementing a ICallHandler obsolete when using custom IInterfaceBehaviors?
As I understand both build up a pipeline for interception.
What is the benefit of using ootb callhandlers and custom callhandlers over IInterfacebehaviors?
I don't want it to be like this:
unity.RegisterType<IMyService, MyService>(
new ContainerControlledLifetimeManager(),
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<OutputInterceptionBehavior>());
rather like this (pseudo code):
unity.addInterceptor<InterfaceInterceptor>()
.addMachingRule<namespace>("mynamespace")
.addBehaviors(...);
So it is partly possible using Unity's RegistrationByConvention.
As far as I have understood, you can only do simple mappings.
For more complex mappings, for example using various InjectionMembers, you have to map them manually.
You have to inherit from RegistrationConvention to build your own convention implementation.
public class UnityRegistrationByConventions : RegistrationConvention
{
private readonly IUnityContainer _container;
List<string> _assemblyNameFilter;
List<string> _namespaceFilterForClasses;
public UnityRegistrationByConventions(IUnityContainer container, List<string> assemblyNameFilter = null, List<string> namespaceFilterForClasses = null)
{
_container = container;
_assemblyNameFilter = assemblyNameFilter;
_namespaceFilterForClasses = namespaceFilterForClasses;
}
public override Func<Type, IEnumerable<Type>> GetFromTypes()
{
return WithMappings.FromMatchingInterface;
}
public override Func<Type, IEnumerable<InjectionMember>> GetInjectionMembers()
{
return (t => new List<InjectionMember>(){
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<LoggingInterceptionBehavior>(), // 1
new InterceptionBehavior<ExceptionInterceptionBehavior>(), // 2
new InterceptionBehavior<CachingInterceptionBehavior>(), // 3
new InterceptionBehavior<ValidationInterceptionBehavior>()} as IEnumerable<InjectionMember>);
}
public override Func<Type, LifetimeManager> GetLifetimeManager()
{
return t => WithLifetime.Transient(t);
}
public override Func<Type, string> GetName()
{
return (type => (this._container.Registrations.Select(x => x.RegisteredType)
.Any(r => type.GetInterfaces().Contains(r) == true) == true) ? WithName.TypeName(type) : WithName.Default(type));
}
public override IEnumerable<Type> GetTypes()
{
var allAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => _assemblyNameFilter.Contains(a.FullName.Split(',')[0]));
List<Type> allClasses = new List<Type>();
foreach (var assembly in allAssemblies)
{
var classArray = assembly.GetTypes().Where(t => t.IsPublic &&
!t.IsAbstract &&
t.IsClass == true &&
_namespaceFilterForClasses.Contains(t.Namespace));
if (classArray != null && classArray.Count() > 0)
allClasses.AddRange(classArray);
}
return allClasses;
}
}
and apply the convention like this
var rby = new UnityRegistrationByConventions(unityContainer, assFilter, classNamespaceFilter);

How to test a class with delegate in constructor using Moq

Can someone explain to me how to create an instance of this component in a Moq TestMethod? Here is the definition of the class. I need to test the ProcessAutomaticFillRequest method.
public class AutomaticDispenserComponent : IAutomaticDispenserComponent
{
private readonly Lazy<IMessageQueueComponent> _messageQueueComponent;
protected IMessageQueueComponent MessageQueueComponent { get { return _messageQueueComponent.Value; } }
public AutomaticDispenserComponent(Func<IMessageQueueComponent> messageQueueComponentFactory)
{
_messageQueueComponent = new Lazy<IMessageQueueComponent>(messageQueueComponentFactory);
}
public void ProcessAutomaticFillRequest(FillRequestParamDataContract fillRequestParam)
{
if (fillRequestParam.PrescriptionServiceUniqueId == Guid.Empty)
throw new InvalidOperationException("No prescription service was specified for processing fill request.");
if (fillRequestParam.Dispenser == null)
throw new InvalidOperationException("No dispenser was specified for processing fill request.");
var userContext = GlobalContext.CurrentUserContext;
var channel = string.Format(Channel.FillRequest, userContext.TenantId,
userContext.PharmacyUid, fillRequestParam.Dispenser.DeviceAgentUniqueId);
NotificationServer.Publish(channel, fillRequestParam);
}
Here is how I started my test, but I don't know how to create an instance of the component:
[TestMethod]
[ExpectedException(typeof (InvalidOperationException))]
public void FillRequestFailsWhenPrescriptionServiceUniqueIdIsEmpty()
{
// How do I create an instance of automatiqueDispenserComponent here
// since there is Func as constructor parameter?
var fillRequestParam = new FillRequestParamDataContract
{
PrescriptionServiceUniqueId = Guid.Empty
};
_automaticDispensercomponent.ProcessAutomaticFillRequest(fillRequestParam);
// ...
}
Updated the answer based on the comments below. You need to mock the Func parameter for the test.
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void FillRequestFailsWhenPrescriptionServiceUniqueIdIsEmpty()
{
var mockMsgQueueComponent = new Mock<Func<IMessageQueueComponent>>();
var _automaticDispensercomponent = new AutomaticDispenserComponent
(mockMsgQueueComponent.Object);
var fillRequestParam = new FillRequestParamDataContract
{
PrescriptionServiceUniqueId = Guid.Empty
};
_automaticDispensercomponent.ProcessAutomaticFillRequest(fillRequestParam);
}

Moq VerifySet(Action) strange behaviour

I use Moq to test some behaviour. I want to verify set view's model property as new instance of Message class:
[TestFixture]
public class MessageFormPresenterTests
{
private NameValueCollection queryString;
private Mock<IDatabase> mockDatabase;
private Mock<HttpContextBase> mockHttpContext;
private Mock<HttpRequestBase> mockRequest;
private Mock<HttpResponseBase> mockResponce;
private Mock<IMessageFormView> mockView;
private MessageFormPresenter presenter;
[SetUp]
public void SetUp()
{
this.queryString = new NameValueCollection();
this.mockDatabase = new Mock<IDatabase>();
this.mockHttpContext = new Mock<HttpContextBase>();
this.mockRequest = new Mock<HttpRequestBase>();
this.mockResponce = new Mock<HttpResponseBase>();
this.mockView = new Mock<IMessageFormView>();
this.mockHttpContext.SetupGet(c => c.Request).Returns(this.mockRequest.Object);
this.mockHttpContext.SetupGet(c => c.Response).Returns(this.mockResponce.Object);
this.mockRequest.SetupGet(r => r.QueryString).Returns(this.queryString);
this.presenter = new MessageFormPresenter(this.mockView.Object) { Database = this.mockDatabase.Object, HttpContext = this.mockHttpContext.Object };
}
[Test]
public void ViewLoad_QueryStringNotHasMessageIdParameter_PopulateViewModelAsNewMessage()
{
// Act
this.mockView.Raise(v => v.Load += null, new EventArgs());
// Assert
this.mockView.VerifySet(v => v.Model = It.Is<Message>(m => m.Id == 0));
}
}
But this test pass even if i not write this functionality in my MessageFormPresenter. When i set breakpoint to action call (v.Model = It.Is(m => m.Id == 0)) and debug my test, Model property returned as "Castle.Proxies.MessageProxy" type and has all properties with default values (value of Id property is 0, of course).
Why is this happening? I don't setup anything to return and Moq should return null by default.
P.S. Excuse me for my poor english. I hope you understand what i'm talking about)
UPDATE1: MessageFormPresenter class:
public class MessageFormPresenter : Presenter<IMessageFormView>
{
private IDatabase database;
public MessageFormPresenter(IMessageFormView view)
: base(view)
{
View.Load += this.View_Load;
}
public IDatabase Database
{
get { return this.database ?? (this.database = DatabaseFactory.DatabaseInstance); }
set { this.database = value; }
}
private void View_Load(object sender, EventArgs e)
{
int messageId;
var messageParam = Request.QueryString[QueryParamNames.MessageId];
if (messageParam == null)
{
View.Model = new Message();
return;
}
if (!View.IsAdmin)
{
Response.Redirect(PageUrls.AccessDenied, true);
return;
}
if (int.TryParse(
messageParam,
NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite,
CultureInfo.InvariantCulture,
out messageId))
{
View.Model = this.Database.Single<Message>(messageId);
}
else
{
Response.Redirect(PageUrls.DefaultPage, true);
}
}
}
Base class Presenter<IMessageFormView> provided by WebFormsMvp framework.
UPDATE2: If i use strict behaviour TargetInvocationException will be thrown in base constructor of MessageFormPresenter, even if i setup all properties of Mock<IMessageFormView>.

TDD problem in ASP.NET MVC3 (with DI)

I am attempting to write some Tests for a small project of mine but they seem to fail (I am starting with 1 test 'Create_Class')
I use the repository pattern and use Constructor Dependency Injection:
public KlasController() {
db = ObjectContextPerHttpRequest.Context;
KlasRepo = new KlasRepository(db);
LesRepo = new LesRepository(db);
OpdrachtRepo = new OpdrachtRepository(db);
}
//dependency injection constructor
public KlasController(IKlasRepository KlasRepo, ILesRepository LesRepo,
IOpdrachtRepository OpdrachtRepo) {
this.KlasRepo = KlasRepo;
this.LesRepo = LesRepo;
this.OpdrachtRepo = OpdrachtRepo;
}
here is my TestClass with testinitializer (which runs before every test) and the first test
[TestClass()]
public class KlasControllerTest
{
private KlasController Controller;
private IOpdrachtRepository OpdrachtRepo;
//Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
OpdrachtRepo = new DummyOpdrachtRepository();
Controller = new KlasController(new DummyKlasRepository(),
new DummyLesRepository(), OpdrachtRepo);
Opdracht TestOpdracht = new Opdracht
{
OpdrachtID = 1,
VakID = 1,
StamNummer = "im1"
};
Vak TestVak = new Vak { VakID = 1, VakNaam = "FOOP" };
TestOpdracht.Vak = TestVak;
OpdrachtRepo.addOpdracht(TestOpdracht);
}
/// <summary>
///A test for Index
///</summary>
[TestMethod()]
public void CreateKlasDirectsToToonKlassen()
{
Klas Klas = new Klas { KlasNaam = "2dNet" };
RedirectToRouteResult view = Controller.Create(1) as RedirectToRouteResult;
Assert.IsNotNull(view);
Assert.AreEqual("ToonKlassen", view.RouteValues["action"]);
}
}
at the moment I get a nullreferenceException on the view (assert.isNotNull fails)
and here is one of my DummyRepository's:
class DummyOpdrachtRepository : IOpdrachtRepository
{
List<Opdracht> opdrachten;
public DummyOpdrachtRepository()
{
opdrachten = new List<Opdracht>();
}
public void addOpdracht(Opdracht opdracht)
{
opdrachten.Add(opdracht);
}
public string GetDocentID(int OpdrachtID)
{
var opdracht = opdrachten.Where(o => o.OpdrachtID == OpdrachtID).FirstOrDefault();
return opdracht.StamNummer;
}
public Opdracht Find(int id)
{
return opdrachten.Where(o => o.OpdrachtID == id).FirstOrDefault();
}
}
Normally I should have written the tests Before writting the code, I know (and I am convinced off TDD, as I have used it successfully in my latest Java-project). but it just doesn't seem to work..
here is the code for KlasController.Create action
public ActionResult Create(int id) //id = opdrachtID
{
var Opdracht = OpdrachtRepo.Find(id);
Vak vak;
if(Opdracht != null)
vak = Opdracht.Vak;
else
throw new NullReferenceException("Deze opdracht werd niet gevonden");
return View(new CreateKlasModel(id,vak));
}
I know this is a lot of code, but I really want to make this work.
Thanks for helping me out in advance :)
As vladimir77 already says in his comment, the method public ActionResult Create(int id) is of type ViewResult, so either you change you method to do areturn RedirectToRoute() or you change your test to
ViewResult view = Controller.Create(1);
Assert.IsNotNull(view);
A ViewResult can not be cast as a RedirectToRouteResult.

Resources