Testing S#arp Lite Repositories with Moq

One pending matter I’ve always had is to improve my testing skills, there I said it. I test, but not as much as I should. When I say test, I mean Unit Test, not just test the application by launching it and starting to poke it. One thing that I found to be a really outstanding idea with S#arp Lite is that repositories eliminated many complications. If you had a repository and needed to run a query against it, just call GetAll and throw some Linq at. Grated, it assumed that the Linq provider for the underlaying data model was mature, but with NHibernate and EntityFramework being the two ORM of my choice always, that seems like a fair assumption.

However, this has a downside, I tried to test the repositories and had a really rough time getting to test a repo that was using an underlying IQueryable item. However, this became quite clear with time, and now I can test my repos. Let’s make a fairly simple test scenario. Let’s assume I have a user class, with a few standard properties, pretty much like this one:

public class User : Entity
{
 public virtual string Password { get; set; }

 public virtual string Email { get; set; }

 public virtual bool Blocked { get; set; }

 public virtual int LoginCount { get; set; }
} 

Now, I have a class called Membership that handles my Membership logic, that is, logging users, blocking them after a couple of bad logins, etc. That class should look like this:

public class Membership
{
 IRepository<User> _usersRepository;

 public Membership( IRepository<User> usersRepository )
 {
  _usersRepository = usersRepository;
 }
 
 public bool IsValidUser( string email, string password )
 {
  //create test first!
  return false;
 }
} 

Now, we need to create a test case. Let’s call it, MembershipTests

[TestFixture]
public class MembershipTests
{
 [TestFixtureSetUp]
 public void SetupTestEnvironment()
 {
 
 }
}

Now, I want to create a Mock repository to pass it along to my test Membership class, but I need to do it so that it simulates the data backed without touching my actual data nor getting too slow. Obviously we need a list, but not just any list, we need a list that can pose for a Repository or at least fake it. That’s why we need to create this sort of list, a QueryableList:

public class QueryableList<T, TId> : List<T>, IQueryable<T> where T : EntityWithTypedId<TId>
{
 #region Constructors
 public QueryableList()
 { }

 public QueryableList(IEnumerable<T> source)
  : base(source)
 { } 
 #endregion

 #region IQueryable<T> implementation
 public Expression Expression
 {
  get { return ToArray().AsQueryable().Expression; }
 }

 public Type ElementType
 {
  get { return typeof(T); }
 }

 public IQueryProvider Provider
 {
  get { return ToArray().AsQueryable().Provider; }
 }
 #endregion

 public void UpdateEntity(T entity)
 {
  var index = -1;

  for (var i = 0; i < Count; i++)
   if (this[i].Equals(entity))
    index = i;

  if (index == -1)
   Add(entity);
  else
   this[index] = entity;
 }
} 

Voila! We have a List that directly implements IQueryable, which is a good thing, not a hard thing to do, but it will help us a lot. We need to get the entity of the List and the Id that is going to be used on the list to keep it as generic as possible, so when we need to test a repo of entities with typed id’s, we won’t have to rewrite much. The UpdateEntity method will mimic the SaveOrUpdate method we have on our repo using the Equals method to invoke the Equality comparer provided by S#arp Lite. Now, we need to setup our Mocks. We go back to the TestSetup and let’s setup our environment:

[TestFixture]
public class MembershipTests
{
 private Membership _membership;
 
 [TestFixtureSetUp]
 public void SetupTestEnvironment()
 {
  var usersMockedRepo = new Mock<IRepository<User>>();
  
  var users = new List<User> { new User{ Blocked = false, Email = "david@someplace.com", Password = "a password" } };
  var list = new QueryableList<T, int>(users);
  
  //Mock GetAll
  usersMockedRepo.Setup(x => x.GetAll()).Returns(list);
  
  //Mock the Get
  usersMockedRepo.Setup( x => x.Get( It.IsAny<int>() ))
      .Returns( (int id) => list.AsQueryable()
      .SingleOrDefault(x => x.Id.Equals(id)));
  
  //Mock the SaveOrUpdate using our own
  usersMockedRepo.Setup(x => x.SaveOrUpdate(It.IsAny<T>()))
      .Callback((T entity) => list.UpdateEntity(entity));
      
  //Mock the delete
  usersMockedRepo.Setup(x => x.Delete(It.IsAny<T>())).Callback((T entity) => list.Remove(entity));
  _membership = new Membership(usersMockedRepo.Object);
 }
}

Now, we have setup our very own mocked repository. We need to make a test now for the IsValidUser method we left before. Let’s write a simple test case:

[TestCase]
public void CheckBasicAuthentication()
{
 var checkValidUser = Membership.Instance.IsValidUser("david.conde@gmail.com", "a password");
 var checkInvalidUser = Membership.Instance.IsValidUser("david.conde@gmail.com", "another password");

 Assert.AreEqual(checkInvalidUser, false);
 Assert.AreEqual(checkValidUser, true);
}

And that’s it! We have our own test and we can now create as many test cases as we want all relying on a simple structure like a list. There is one final thought here, which came to mind while reading this StackOverflow post. The idea is to put the setup into a helper method, so we can reuse it with different test scenarios:

Please note that the following code can induce headaches 🙂

public static class MockExtensions
{
 public static void SetupIQueryableTypedRepository<T, TId>
  (this Mock<IRepositoryWithTypedId<T, TId>> mockObject, IEnumerable<T> source)
  where T : EntityWithTypedId<TId> where TId : IComparable
 {
  var list = new QueryableList<T, TId>(source);

  mockObject.Setup(x => x.GetAll()).Returns(list);
  mockObject.Setup(x => x.Get(It.IsAny<TId>())).Returns((TId id) => list.AsQueryable().SingleOrDefault(x => x.Id.Equals(id)));

  mockObject.Setup(x => x.SaveOrUpdate(It.IsAny<T>())).Callback((T entity) => list.UpdateEntity(entity));
  mockObject.Setup(x => x.Delete(It.IsAny<T>())).Callback((T entity) => list.Remove(entity));
 }

 public static void SetupIQueryableRepository<T>(this Mock<IRepository<T>> mockObject, IEnumerable<T> source)
  where T : Entity
 {
  var list = new QueryableList<T, int>(source);

  mockObject.Setup(x => x.GetAll()).Returns(list);
  mockObject.Setup(x => x.Get(It.IsAny<int>())).Returns( (int id) => list[id] );
  
  mockObject.Setup(x => x.SaveOrUpdate(It.IsAny<T>())).Callback( (T entity) => list.UpdateEntity(entity) );
  mockObject.Setup(x => x.Delete(It.IsAny<T>())).Callback((T entity) => list.Remove(entity));
 }
}

Now, we can reduce our Setup method to this:

[TestFixtureSetUp]
public void SetupTestEnvironment()
{
 var usersMockedRepo = new Mock<IRepository<User>>();
 var users = new List<User> { new User{ Blocked = false, Email = "david@someplace.com", Password = "a password" } };
 
 usersMockedRepo.SetupIQueryableRepository(users);
 _membership = new Membership(usersMockedRepo.Object);
}

If you just want to be able to test your S#arp Lite repositories using this, then just get this extension to your code, set your mocked repositories using this idea and done! If you have any other thoughts, let me know on the comments!

S#arpLite: “At least one ISessionFactory has not been registered with IoC”, Darn with the redirections…

Yesterday I installed ASP .NET MVC 4 beta so I can play with it for a couple days. To be honest, I haven’t built one simple app because I haven’t had the time to do it, but I popped up my Visual Studio 2010 today and booted a S#arp lite project from the template. As usual, I made my move to Fluent nHibernate but when I loaded the project:

After spending a couple hours digging my way into my machine and debugging I went into the S#arp Lite discussion group and found this post of somebody having the same issue, finally the last answer hit the nail:

Have you installed MVC4 on you machine? If yes, check reference in Init project, it references MVC4 whereas Web project references MVC3.

Mmmmm… I did… so I tried this…

<dependentAssembly>
 <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
 <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
 

Voilà! It works now… Darn with the redirections…

SharpLite scaffolding is out! (beta)

This simple post is to show how to gt started using s small Scaffolder I made for SharpLite projects. It takes as input a contoller name and generates the controller to use with a SharpLite repository and the views using the regular Mvc3 scaffolding from Steven Sanderson. As a disclaimer, my code is just some tweaks different from the actual scaffolder from Steven Sanderson, and I haven’t tested it too much so don’t take this as a final product. I will, however keep working on this as time goes by and hopefully we may add some more new stuff!

Ok, enough of that! Just install the package from the NuGet feed…

Install-Package SharpLite.Scaffolding

Fire up your Package Manager Console and assuming you have an entity called Product and you want to make your own controller to manage products, just type:

 Scaffold slController ProductsController 

That’s it! This is a quite quick and dirty Scaffolder, but as I said, I will keep doing some more stuff into it. If you have any doubts or issues, feel free to comment or just send me a mail.

EDIT: For those of you who want to check out the source code of the scaffolders and follow the project, the code is hosted here

Using Sharp Lite with Fluent nHibernate

One thing I didn’t liked too much when first met S#arp Lite was the fact that Billy McCafferty decided to drop Fluent nHibernate as the defacto mapper for entities. There was a big discussion on the matter of nHibernate making it’s own fluent (or was it Loquacious?) API to map entities on a lot of places, and finally James Gregory, the man who gave us Fluent nHibernate spoke on the matter of nHibernate making an API that looked a lot like his.

The conclusion is pretty simple, Fluent nHibernate is not dead, not even close, there are a lot of folks (me included) that like it and we are not willing to let it go. Having said that, I wanted to integrate my Fluent nHibernate into S#arp Lite, and just as Billy said, is a dead simple thing to do, still will share it here.

The first thing you need to do is to reference the Fluent nHibernate library from your NorthwindDemo.NHibernateProvider project, so you can use it there. After that, you can make your own mappings on the provider. If you don’t know what is a Fluent Mapping, you should read this wiki before you start here. Now that we have our mappings made, we need to change the nHibernate boot process found in NHibernateInitializer so we use Fluent nHibernate instead. Go to the NHibernateInitializer class and change the code for this:

public static Configuration Initialize()
{
 var cnf 
          = Fluently.Configure()
      .Database(MySQLConfiguration.Standard.ConnectionString( 
    x => x.Database("MyDb")
          .Username("MyUserName")
          .Password("MyPassword")
          .Server("MyServer"))
   )
       .Mappings( m => m.FluentMappings.AddFromAssemblyOf&lt;CustomerMapping&gt;());

 var configuration 
          = cnf.BuildConfiguration()
        .Proxy( p => p.ProxyFactoryFactory&lt;DefaultProxyFactoryFactory&gt;() )
        .CurrentSessionContext&lt;LazySessionContext&gt;();

 return configuration;
} 
 

Notice that I’m not using SQL Express like the default install uses, I’m using MySQL instead. The magic of the thing is on the line:

.Mappings( m => m.FluentMappings.AddFromAssemblyOf<customerMapping>()); 
 

Here, I’m telling FNH to load all the mappings specified in the assembly of CustomerMapping, which is one of my entities’ mappings. After that, we register the DefaultProxyFactoryFactory to manage the lazy loading, which basically gets rid of the old nHibernate.Castle so we don’t have to use an external loader for proxy classes. With this configuration, you should be on your way to use Fluent nHibernate with your S#arp Lite project.

Finally, there is one thing. I think, not so sure though, that there is a version of Fluent NH for nHibernate 3.2, however, if you are using an older one, like me!, I’m using v1.2 which looks for nHibernate 3.1, you will need to make an Assembly redirect, which is easy, just lk in your web.config file for this line:

<runtime>
 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
   <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
   <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
 </assemblyBinding>
</runtime>
 

And change it for this one:

<runtime>
 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
   <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
   <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
   <assemblyIdentity name="NHibernate" publicKeyToken="aa95f207798dfdb4" culture="neutral" />
   <bindingRedirect oldVersion="0.0.0.0-3.1.0.4000" newVersion="3.2.0.4000" />
  </dependentAssembly>
 </assemblyBinding>
</runtime>
 

The basic idea is to tell the system that when someone (FNH) asks for nHibernate from version 0.0.0.0 to 3.1.0.4000 the assembly to resolve is version 3.2.0.4000, so the binding is done properly. This should be it, you should have your own S#arp Lite project running on Fluent nHibernate!!

Happy coding! And as usual, comenting is not forbidden 😉

Booting Sharp Lite and autogenerating Db with nHibernate

When facing a new project, there are many things to consider, but there is no doubt that the words most mentioned and given more buzz are how to accomplish a scalable and maintainable solution without builing the next Amazon for our first version. However, trying to make a solution that is able to grow over time and adapt to new requirements is not an easy task, it’s indeed very tricky business. That’s why there are frameworks, mainly because there are a bunch of guys willing to help those who can’t (or won’t) get into building their own foundation to make a project.

And here is where S#arpArchitecture enters. S#arpArchitecture is project started by Billy McCafferty, a developer/architect well versed on the matter how made a super duper framework to deploy ASP .NET applications. The framework was consistent with several best practices he wrote on a CodeProject article on how to accomplish a nice setup of a project using nHibernate. The thing with S#arpArchitecture is that it was somehow a bit coupled into nHibernate, altough this didn’t seemed to matter at that point because nHibernate was (and IMHO is, but won’t get into that) the best way to accomplish ORM with a .NET project. However, time has changed and EntityFramework is a strong project, not to mention that is handled by the man, we also have now the NoSql fever and there are other stuff that may be yet to come and S#arpArchitecture had to evolve to remove the direct dependencies from nHibernate but as any old project moving away from the original idea has been a difficult business and the most important thing is that to be able t setup a S#arpArchitecture install using other thing than nHibernate, you’ll have to be very versed on topics such as IoC, design patterns, nHibernate itself, so you know what to remove and what not to remove and many other dark stuff.

Because of all these nasty reasons, Billy McCafferty decided to start yet another framework called S#arp Lite. The intention here was to be able to make a decent framework available for a broader audience of developers who didn’t had to be very versed on deep matters of architecture.

So, if you want to make an ASP .NET MVC 3 app and looking for a nice development framework, you should make a run for S#arp Lite and try it out. The first thing you’ll need is to read the blog post where Billy explains why he had to make S#arp Lite despite the fact that we already had a S#arpArchitecture, once you’ve read that, you should also get the basics on S#arp Lite also explained by Billy in this post. If, however, you don’t want to read any of those and just want to jumpstart into S#arp Lite, then the idea would be to:

Before anything, the sample app is found inside the S#arp Lite file downloaded from Github, on the folder called Example, the project is named MyStore. Now, to set up your database for the sample app, you can make two things, one I like it, the other not so much. Before getting to that, make sure that you have a SQL Server database to play with and get your connection string. Mostly if your DB is the integrated SQL Server Express DB that comes with Visual Studio, your connection string will look like this one:

Data Source=localhostsqlexpress;Initial Catalog=SampleDb;Integrated Security=True
 

The only thing that may change is the Initial Catalog, which is basically up to your choosing. Now that we know the connection string, we need to tell S#arp Lite what is it, so open the web.config file found on MyStore.Web and look for the line where says:

<connectionStrings>
   <add name="MyStoreConnectionString" connectionString="YOUR_CONNECTION_STRING" />
</connectionStrings>
 

And yes, you guessed it, change where it says YOUR_CONNECTION_STRING for the actual connection string.

Now we just need to setup our DB, for which you have two ways. The first way is the simplest one, which is to use a SQL server administration tool, the Management Studio Express included with the Express version of SQL Server express 2008 is just fine, and run the sql file you can find inside the example project on the folder called “MyStore.DB” et voilà! The project can now be run.

As a side note, the last time I downloaded S#arp Lite (v0.42), when setting up the sample project and compiling, you’d get 11 errors regarding tests and test classes that cannot be found, don’t despair! Just go into MyStore.Tests and remove the reference to nunit.framework and add it again, the assembly should be in your lib folder outside of the project. Now you can run the demo without issues!

Now the other way, which I like a lot more is to use nHibernate to generate your database, which is so cool! And since nHibernate is also very cool, this is a very simple process. Just go into your project called “MyStore.NHibernateProvider” and look for the class called NHibernateInitializer. Just like the name indicates this fellow handles the initialization of nHibernate and we will also generate the DB with it. Go into the class and add the method that will handle DB initialization:

public static void CheckAndBuilDb(Configuration cfg)
{
 var schemaValidator = new SchemaValidator(cfg);

 try {
  schemaValidator.Validate();
 }
 catch (Exception) {
  var schemaBuilder = new SchemaExport(cfg);
  //drop in case of old one
  schemaBuilder.Drop(false, true);
  schemaBuilder.Create(false, true);
 }
}
 

Without entering into unnecessary gory details, the idea is to check if the existent DB is up to date and if is not, drop it and regenerate a new one. This does bring a bad side effect, which is the issue of migrating from one version into another. That problem can be fixed doing some nHibernate-fu, but we won’t get into that for now. Build and run and your database will be automatically generating against the mapped entities! Cool uh?

This is pretty much just about it, I’ll make a follow up post with some more stuff on how to get going with S#arp Lite and Fluent nHibernate.