Configure AutoMapper to return Mock in test layer - tdd

In my app, all domain classes follow the standardization:
All implement the interface IEntity
Id properties are protected*
The properties of type IList are protected and initialized in the constructor.
Below is a classic example of a domain entity:
public class CheckListItemTemplate : IEntity
{
public virtual int Id { get; protected set; }
public virtual string Text { get; set; }
public virtual CheckListItemTemplate Parent { get; set; }
public virtual IList<CheckListItemTemplate> Itens { get; protected set; }
public CheckListItemTemplate()
{
Itens = new List<CheckListItemTemplate>();
}
public void AddItem(CheckListItemTemplate item)
{
item.Parent = this;
Itens.Add(item);
}
}
*This is because the id is generated by the database and not run the risk of some developer trying to set this property.
Test project
We have a fake generic repository used in the tests:
public class Repository<T> : IRepository<T>
where T : class, IEntity
{
private readonly IDictionary<int, T> _context = new Dictionary<int, T>();
public void Delete(T obj)
{
_context.Remove(obj.Id);
}
public void Store(T obj)
{
if (obj.Id > 0)
_context[obj.Id] = obj;
else
{
var generateId = _context.Values.Any() ? _context.Values.Max(p => p.Id) + 1 : 1;
var stub = Mock.Get<T>(obj);
stub.Setup(s => s.Id).Returns(generateId);
_context.Add(generateId, stub.Object);
}
}
// ..
}
As you can see in the Store*, all test objects (of type IEntity) should be a Mock**. This is because in UI project, when we save an object NHibernate updating the property Id. In testing project we have to do this manually, and we have no way to set the property Id with a new value, so the solution was mock the entire object to the Get property Id correspond to the new Id . Exactly what does this line stub.Setup(s => s.Id).Returns(generateId).
*By convention, objects with Id <= 0 are new and Id> 0 are existing objects in the database.
**For Mock I use Moq.
Id as protected
The biggest problem occurs because of Id property and the fact that is protected.
When we talk about the designer, is a great approach but this brings huge inconvenience when we test our application.
For example, in a test that I'm writing I need my Fake repository with some data already populated.
Code
Follow me. I have the following classes (+ CheckListItemTemplate shown above.)
public class Passo : IEntity
{
public int Id { get; protected set; }
public virtual IList<CheckListItemTemplate> CheckListItens { get; protected set; }
}
public class Processo : IEntity
{
public virtual int Id { get; protected set; }
public virtual Passo Passo { get; set; }
public virtual IList<CheckListItem> CheckListItens { get; protected set; }
}
After saving the Processo, the first Passo is associated with the Processo: (sorted by Ordem field following field CreateAt)
model.Passo = PassoRepositorio.All().OrderBy(p => p.Ordem).ThenBy(p => p.CreateAt).First();
model.CheckListItens.Clear();
Parallel.ForEach(Mapper.Map<IList<CheckListItem>>(model.Passo.CheckListItens), (it) => model.AddCheckListItem(it));
This code is running whenever you save a new Processo. For any test that creates a new Processo, this code will be executed!
Test
If we have to create a test that creates a new Processo, our first goal is to populate the PassoRepositorio repository with some dummy data*, with Passos and CheckListItemTemplates specifically for the above code does not fail**.
*To populate objects with dummy data I use AutoFixture.
** Will fail if no Passo is found in the repository .First() and this Passo has no checklist Mapper.Map(model.Passo.CheckListItens).
So we need a repository of Passos and each Passo with a list of CheckListItens.
Remember that every object IEntity should be an Mock<> so we can mock property Id
First attempt
First configure my TestInitialize to populate my repository with some dummy data:
var fix = new Fixture();
var listPassos = fix.Build<Mock<Passo>>()
.Do((passo) => {
passo.SetupProperty(x => x.Nome, fix.Create<string>());
passo.SetupGet(x => x.CheckListItens).Returns(
fix.Build<CheckListItemTemplate>() // Needs to a Mock<>
.With(p => p.Texto)
.OmitAutoProperties()
.CreateMany(5).ToList()
);
})
.OmitAutoProperties()
.CreateMany(10);
foreach (var item in listPassos)
passoRepository.Store(item.Object);
Then I can run the tests:
[TestMethod]
public void Salvar_novo_processo_modificar_data_atendimento_passo_atual()
{
// Arrange
var fix = new Fixture();
var vm = fix.Create<ProcessoViewModel>();
//Act
Controller.salvar(vm); // Problem here. (For convert ProcessoViewModel to Processo I use a AutoMaper. In repository needs destination to be a Mock<Processo>
var processo = Repository.Get(p => p.DataEntrada == vm.DataEntrada && p.ProximoAtendimento == vm.ProximoAtendimento);
//Asserts
processo.Should().NotBeNull();
processo.Passo.Should().NotBeNull();
}
Questions
We create a list of 10 Passo where each Passo is actually is a Mock<>, great! But:
For each Passo have a list of 5 'Mock' items, and each Id should be 1, 2, 3, 4 and 5 (in that order). How to achieve this? How to obtain this list of IList<Mock<>> inside a Mock<> with Id already filled? That is, the configuration
passo.SetupGet(x => x.CheckListItens).Returns( ???
The responsible for creating objects in my controller, basically uses AutoMapper to convert my ViewModel object to an object that can be persisted Model in my repository:
model = Mapper.Map<TModel>(vm);
The problem is that my repository Fake can not save an object IEntity, just Mock<IEntity>. How to configure AutoMapper to always return a Mock<>?

Answer for Question 1: In case this helps, you can use a closure to maintain a running counter to use as an id. For example:
class MyTestClass
{
int _runningCounter = 0;
public void SomeTest()
{
/* ... some other code including mock creation ...*/
someMock.Setup(m => m.ReturnNewWidgetEntity())
.Returns(() => new WidgetEntity{ Id= ++_runningCounter });
}
}
Each time ReturnNewWidgetEntity is called on the mocked object, the Id property will be set to an increased number.
Answer for Question 2: I would suggest that rather than having a concrete dependency on the Mapper class, you replace this with an injected dependency on IMapperEngine. Richard Dingwall explains the technique here: http://richarddingwall.name/2009/05/07/mocking-out-automapper-with-dependency-injection/
Basically you register Mapper.Engine as the singleton implementation of IMapperEngine in your container and then in your unit tests mock it so that it gives you the required Mock<> classes.
I hope one or both of these answers at least give you food for thought. It was a bit difficult to follow your whole example, to be honest!

Related

ASP.NET Boilerplate: What is the best solution for Four eyes principle

I want to add 4 eyes principle to ASP.NET Boilerplate framework. That means every change on Role, User,.. need to be approved (by another admin) before applied to the system. I have searched for some time but no answer. So what is the best solution for this flow?
Can I create the same tables with Abp tables (dbo.AbpUser_Temp, etc) and the all the changes will be stored in these tables? Is there any better solution?
Example: In the application, Admin1 has created a user named User1. But this user cannot login to the application until he was approved by Admin2.
Simple Workflows
Example: In the application, Admin1 has created a user named User1. But this user cannot login to the application until he was approved by Admin2.
Simple workflows like these can be appropriately handled by a property and a method:
public class User : AbpUser<User>
{
public bool IsApproved { get; set; }
public void Approve(User approver)
{
if (approver.Id != CreatorUserId)
{
IsApproved = true;
}
}
}
Complex Workflows
Complex workflows like "every change" can do this instead of _Temp tables:
public abstract class ChangeBase : Entity<long>, IExtendableObject
{
public string EntityTypeAssemblyQualifiedName { get; set; }
public string EntityIdJsonString { get; set; }
public long ProposerUserId { get; set; }
public long? ApproverUserId { get; set; }
public string ExtensionData { get; set; }
}
public class Change : ChangeBase
{
[NotMapped]
public Type EntityType => Type.GetType(EntityTypeAssemblyQualifiedName);
[NotMapped]
public object EntityId => JsonConvert.DeserializeObject(EntityIdJsonString, EntityHelper.GetPrimaryKeyType(EntityType));
[NotMapped]
public bool IsApproved => ApproverUserId.HasValue && ApproverUserId != ProposerUserId;
[NotMapped]
public IDictionary<string, string> ChangedPropertyValuePairs => JObject.Parse(ExtensionData).ToObject<Dictionary<string, string>>();
public Change(EntityIdentifier changedEntityIdentifier, long proposerUserId, IDictionary<string, string> changedPropertyValuePairs)
{
EntityTypeAssemblyQualifiedName = changedEntityIdentifier.Type.AssemblyQualifiedName;
EntityIdJsonString = changedEntityIdentifier.Id.ToJsonString();
ProposerUserId = proposerUserId;
ExtensionData = JObject.FromObject(changedPropertyValuePairs).ToString(Formatting.None);
}
public bool Approve(long approverUserId)
{
if (approverUserId != ProposerUserId)
{
ApproverUserId = approverUserId;
return true;
}
return false;
}
}
Usage:
public class UserAppService // ...
{
private readonly IRepository<Change, long> _changeRepository;
public UserAppService(
IRepository<User, long> repository,
IRepository<Change, long> changeRepository) // : base(repository)
{
_changeRepository = changeRepository;
}
public void ChangeUserName(long userId, string newUserName)
{
// Validation, etc.
var changedPropertyValuePairs = new Dictionary<string, string> {
{ nameof(User.UserName), newUserName }
};
var change = new Change(
new EntityIdentifier(typeof(User), userId),
AbpSession.GetUserId(),
changedPropertyValuePairs
);
_changeRepository.Insert(change);
}
public void ApproveChange(long changeId)
{
// Validation, etc.
var change = _changeRepository.Get(changeId);
if (change.EntityType == typeof(User) && change.Approve(AbpSession.GetUserId()))
{
var user = Repository.Get((long)change.EntityId);
var changedPropertyValuePairs = change.ChangedPropertyValuePairs;
foreach (var changedProperty in changedPropertyValuePairs.Keys)
{
switch (changedProperty)
{
case nameof(User.UserName):
user.UserName = changedPropertyValuePairs[changedProperty];
break;
// ...
default:
break;
}
}
}
}
For development
Separate staging and production environments. Develop on one box, test it, get it reviewed and then deploy to a production box. Simple, effective and language agnostic advice.
Since ASP.NET Boilerplate framework included Entity Framework. You could also leverage migrations.
After you do your development work, and requires you to "update-database", then your SOP should be to have the admin review the (relatively simple) migrations that will be committed.
I hope that helps.
For application flow
There are probably quite a few ways to actually implement this so I'll cover a simple one get your idea's flowing, but keep in mind: The way you need to implement two person integrity must fit how your operating procedures should work, and not the other way around. Development doesn't drive business operations, business use-cases drive development.
Extending existing Identity* classes. Example: The ApplicationUser class (it may be named differently, but it derives from IdentityUser
Create 2 flags (boolean fields) that must be, and can only be turned 'on' by an administrator
a single administrator can only turn on 1 flag. (Which means you also have to store which administrator turned on which flag.)
The flags can be stored in the existing Abp* tables, or you can create a new table
Add logic so that the user is not allowed to log in unless those 2 flags are both on.
Example: default IdentityUserRole has identified and registered, but can not log in. Once both admin's switch the flags on, elevate the users IdentityUserRole to a role that is allowed to log in.

Using Automapper to map object to realm object with Xamarin and c#

I am creating an Xamarin.iOS app and a Realm database.I would like to keep my POCO objects separate from my RealmObject so what I did was use a repository pattern and within the repository I tried to use AutoMapper to map the POCO to the RealmObject
e.g. (subset)
public class PlaceRepository : IPlaceRepository
{
private Realm _realm;
public PlaceRepository(RealmConfiguration config)
{
_realm = Realm.GetInstance(config);
}
public void Add(Place place)
{
using (var trans = _realm.BeginWrite())
{
var placeRealm = _realm.CreateObject<PlaceRealm>();
placeRealm = Mapper.Map<Place, PlaceRealm>(place);
trans.Commit();
}
}
So, if I debug my code everything maps OK and placeRealm is populated OK but when I commit nothing gets saved to the Realm db. The following is my RealmObject
public class PlaceRealm : RealmObject
{
[ObjectId]
public string Guid { get; set; }
public string Title { get; set; }
public string Notes { get; set; }
}
and this is my POCO Place
public class Place
{
public string Guid { get; set; }
public string Title { get; set; }
public string Notes { get; set; }
}
And AutoMapper is initialized like so:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Place, PlaceRealm>();
cfg.CreateMap<PlaceRealm, Place>();
});
All standard stuff. Has anyone else managed to get something similar working?
Your poco 'Place' is called 'PlaceRealm'. I suspect that is a typo. (made edit)
I suspect that Automapper is instantiating a new object overwriting your original 'placeRealm' object.
Perhaps you could try
Mapper.Map(place, placeRealm);
in place of your current mapping.
which should just copy the values to your already instatiated and tracked object.
(no need to store the return value).
You might also want to make explicit which properties (3) you are mapping as currently Automapper will map all including those in the base class.
On a side note, you may run into performance issues with Automapper. I found it to be the performance bottleneck in some apps. ExpressMapper is a nice alternative.

NHibernate 3 Linq and IUserType

I have a table:
Page (
Id int,
Name nvarchar(50),
TemplateName varchar(50)
...
)
and it's mapped to domain model:
public class Page {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Template Template { get; set; }
}
Note that in the domain model, "Template" property is not of type "string".
The Template class is like this:
public class Template {
public string Name { get; set; }
// other properties...
}
"Templates" are loaded from file system. I have a TemplateManager class:
public class TemplateManager {
public static Template LoadTemplate(string templateName) {
// check if there's a folder named <templateName>
}
}
I can use IUserType to map the "Template" property.
public class PageMap : ClassMapping<Page> {
public PageMap() {
...
Property(c => c.Template, m => {
m.Column("TemplateName");
m.Type<TemplateUserType>();
}
}
}
public class TemplateUserType : IUserType {
public object NullSafeGet(System.Data.IDataReader rs, string[] names, object owner)
{
var templateName = rs[names[0]].AsString();
if (!String.IsNullOrEmpty(templateName))
{
return TemplateManager.LoadTemplate(templateName);
}
return null;
}
}
Okay, so far so good. But the problem is, how can I use Template property in Linq queries?
For exmaple:
var pages = session.Query<Page>().Where(it => it.Template.Name == "MyTemplate");
I think the solution might be to write a class (say TemplatePropertyHqlGenerator) implementing IHqlGeneratorForProperty. This is the linq query extension point provided by NHibernate 3. But how to write this TemplatePropertyHqlGenerator class?
Thanks in advanced!
The IUserType interface lets you define a type which is considered atomic. That is to say, you can then perform direct comparisons between instances of the type and NHibernate will know how to translate them.
E.g. the following query would evaluate:
var template = new Template();
session.Query<Page>().Where(it => it.Template == template);
If you want to define a type which has component values which you can then manipulate, you need to implement the ICompositeUserType interface. This interface requires you define the properties of the type as atomic elements, giving NHibernate the information it needs to understand the specific properties of the type.
As a result, it's a little more complex than IUserType to implement, but it should facilitate what you want to achieve.
Here's an understandable example of implementing the interface for a Money type: http://geekswithblogs.net/opiesblog/archive/2006/08/05/87218.aspx

View and Domain model, where to perform calculation

I just started using View & Domain model design in my MVC web app but got the question where to perform calculations and other View related actions. I will try to give example below.
My Domain Model (Linq2Sql)
public class Product
{
public int Id;
public string Name;
}
The View Model with new UserCount property which I would like to calculate.
public class ProductViewModel
{
public int Id;
public string Name;
public int UserCount;
}
My controller action looks like
public ActionResult _SelectionClientSide_Products()
{
IQueryable<Product> products = _repository.GetProducts(true);
var model = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductViewModel>>(products);
return View(model);
}
I query for data using repository method and get IQueryable<Product> and map it to ProductViewModel list. But I also need to perform another query operation to count users for every queried product and assign all values to ProductViewModel. What design I should follow to achieve this?
The relationship between tables
Products -> Orders - > Users
EDIT
I have decided to remove AutoMapper because it gives more problems than benefits and created my own Builder which contain everything what I need. I make field assign and also add calculation.
public ActionResult _SelectionClientSide_Products()
{
Data = new ProductViewModelBuilder(_repository).Build();
return View(Data);
}
namespace PC.Models
{
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int UsersCount { get; set; }
}
public class ProductViewModelBuilder
{
private readonly IDataAccess _repository;
public ProductViewModelBuilder(IDataAccess repository)
{
_repository = repository;
}
public IQueryable<ProductViewModel> Build()
{
return _repository.GetProducts().Select(p=> new ProductViewModel
{
Id = p.Id,
Name = p.Name,
UsersCount = _repository.CountUsers(p.Id)
});
}
}
}
In my opinion, by the time your Controller has begun it's model setup, there should be no more "logic" or talking to the model. Having a "builder" which queries the model again is bad practice. Not really "breaking" the MVC pattern, but still bad practice. Your ViewModel has a dependency on your DAL. Bad bad boy. :)
If you have to run another query, well that should be encapsulated in the original query. Instead of calling _repository.GetProducts, call a different method which not only gets the products, but get's the count as well. Create a DTO if necessary.
Then your controller should look like:
public ActionResult _SelectionClientSide_Products()
{
var someDto = _repository.GetProductsAndUserCount(true);
var model = Mapper.Map<IEnumerable<SomeDto>, IEnumerable<ProductViewModel>>(someDto);
return View(model);
}
Personally i go for generic repositories over specialized ones, as i don't want a IProductRepository interface with 50 signatures. I opt for LINQ IEnumerable<T> extensions (aka "pipes and filters") which allows complex queries to be built and remain in my domain.
So my version of the above would be:
public ActionResult _SelectionClientSide_Products()
{
var someDto = _productRepository.Find().WithSomeCondition(true).ToSomeDto();
var model = Mapper.Map<IEnumerable<SomeDto>, IEnumerable<ProductViewModel>>(someDto);
return View(model);
}
On a side note, why do you say AutoMapper causes you more problems that benefits? AutoMapper has saved me tons and tons of repetitive code. If you know how to use it properly, it's your best friend. Hands down the most important NuGet package in my current application.

How to create a mock object based on an interface and set a read-only property?

I'm new to TDD. So any help would be appreciated. I'm using NUnit and Rhino mocks.
How can I set the ID value to 1 in my mock object?
I had a look at this: http://www.iamnotmyself.com/2008/06/26/RhinoMocksAndReadOnlyPropertyInjectionPart2.aspx
but the reflection doesn't seem to work against interfaces.
public interface IBatchInfo
{
int ID { get;}
Branches Branch { get; set; }
string Description { get; set; }
}
[SetUp]
public void PerFixtureSetup()
{
_mocks = new MockRepository();
_testRepository = _mocks.StrictMock<IOLERepository>();
}
[Test]
public void ItemsAreReturned()
{
IBatchInfo aBatchItem= _mocks.Stub<IBatchInfo>();
aBatchItem.ID = 1; //fails because ID is a readonly property
aBatchItem.Branch = Branches.Edinburgh;
List<IBatchInfo> list = new List<IBatchInfo>();
list.Add( aBatchItem);
Expect.Call(_testRepository.BatchListActive()).Return(list);
_mocks.ReplayAll();
BatchList bf = new BatchList(_testRepository, "usercreated", (IDBUpdateNotifier)DBUpdateNotifier.Instance);
List<Batch> listofBatch = bf.Items;
Assert.AreEqual(1, listofBatch.Count);
Assert.AreEqual(1, listofBatch[0].ID);
Assert.AreEqual( Branches.Edinburgh,listofBatch[0].Branch);
}
Found the answer here http://haacked.com/archive/2007/05/04/setting-propertybehavior-on-all-properties-with-rhino-mocks.aspx.
Simple, instead of
aBatchItem.ID=1;
use:
SetupResult.For(aBatchItem.ID).Return(1);
Even better if using rhino mocks 3.5:
aBatch.Stub(x => x.ID).Return(0);

Resources