If you don’t see the solution at the top of the Solution Explorer, go to the Tools menu > Options. In the Options window, ensure “Show all settings” is checked, then go to Projects and Solutions on the left and check “Always show solution” on the right:

This time, you don’t need to create a new ASP.NET MVC 3 web application. Instead, open the solution from last time, right click on the solution at the top of the Solution Explorer and choose Add > New Project…:

Choose Visual C# Class Library as the project template and name it CastleFluentNHibernateMvc3.Tests. Once the project has been added to the solution, delete the Class1 class. Next, right click on the Tests project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for NUnit and install it. Also, search for and install Moq.

Once the packages have been downloaded and installed, add a folder to the Tests project named Controllers, then add a class to the Controllers folder named HomeControllerTest. Make this class public and prepend it with the TestFixture attribute, like so:

[TestFixture]
public class HomeControllerTest { }

Finally, we’re ready to write some tests!

Remember, a unit test typically covers a single unit of code. In the case of a MVC application, that means that each action and method deserves its own unit test. Depending on the complexity, some actions and methods deserve several unit tests. Because our application is so simple, however, our unit tests will be relatively simple as well. As you can tell from the previous step, we will be writing unit tests for the actions in our home controller, starting with the Index action. For convenience, here is the code:

We want to make sure that every time the Index action is called the store repository returns a list of stores and the action returns a view. Testing that the action returns a view is simple enough, so at first we might try something like this:

The first thing you’ll notice is that the Tests project requires a reference to CastleFluentNHibernateMvc3, as well as System.Web.Mvc. Once you’ve added these references, Visual Studio will display this compilation error:

'CastleFluentNHibernateMvc3.Controllers.HomeController' does not contain a constructor that takes 0 arguments

The reason we get this error is because we modified the home controller constructor last time to use dependency injection. We did this because we don’t want to use our real repository in our unit tests. Instead, we want to use a fake (or mock) repository. This is where Moq comes in handy, although it does require a little setup before we can use it. First, we need a field to store our fake repository in the HomeControllerTest class, which we need to reset after each test execution:

Download the Visual NUnit extension for Visual Studio. Go to View > Other Windows > Visual NUnit. After compiling the Tests project, select it in Visual NUnit and run the test.

Whichever option you choose, our test should pass with flying colors! Unfortunately, there’s a problem. We’ve made sure our action returns a view, but the view it’s returning is actually the Error view. We can verify this by debugging our test. In Visual Studio, go to Debug > Attach to process… find nunit-agent.exe (if you chose option one above) or VisualNUnitRunner.exe (if you chose option two) in the list of processes and click the Attach button.

Now, we can put a breakpoint in our test and take a closer look at our result. Sure enough, the ViewName is “Error”:

We could have caught this sooner by testing that the view is getting the right model. In this case, our view should be getting a list of stores as its model. We would test for that as follows:

Let’s put a breakpoint in our home controller this time and find out what’s going on. Doing this, we can see that our store repository is not returning any stores. And why should it? Remember, it’s a fake repository! We have to tell our fake repository what to do when it’s queried for a list of stores. But before we do that, make a copy of the Index test and rename it to Index_NoStoresFound. With a little modification, this test can still be useful:

Keeping this test will ensure that the Index action always returns the Error view when our store repository doesn’t return any stores. If this test ever fails (for instance, because the Index action returns the Index view), then something is wrong with our error handling.

Now, let’s fix our Index test. We can use Moq’s Setup method to tell Moq what to return when we ask it for a list of stores:

Previously, I mentioned that dependency injection is important for unit testing. If you are unfamiliar with either of these concepts, then your eyes probably glossed over when you read that sentence. I’m sure you could find many articles that cover unit testing and dependency injection on the interwebs. However, since I try to be newbie friendly (i.e. I am a newbie), I’m going to try to explain – in layman’s terms – the basic ideas behind these concepts. This will also give me a chance to learn more by teaching, which is how I learn best.

NOTE: I won’t be discussing test-driven development here. Some beginners get unit testing and TDD confused, but TDD is a separate topic that deserves its own article at some point in the future.

Unit testing

If you’ve ever done any programming in any language, then you are already familiar with manual testing. You might call it “looking for bugs” or “checking your work,” but it all boils down to launching your software and using it. At first, manual testing is quick and easy. After creating an HTML page, for instance, you would open it in a browser to verify that it looks okay. If it doesn’t, you would have to adjust the HTML until it passes the test. If it does, you might create another page and repeat the process. After that, you would need to add links from each page to the other. Then, you would have to open each page in a browser to verify that the links on each page work.

Here’s what usually happens pretty quickly: you have several pages, each with links to several other pages. Then, without thinking through the ramifications, you change a file name. This tends to happen at the worst possible moments, like right after your pages go live. Of course, it’s possible to test every link on every page every time you make a change like that. But if you are working on a large project, it can become extremely time consuming. Wouldn’t it be nice if there was a way to test every link on every page automatically every time you make a change?

There is a way. It’s called unit testing, and – if implemented correctly – it will save you from breaking changes. The reason it’s called unit testing instead of automatic testing is because it normally involves testing a single unit of code (a method or an action) at a time. To be honest, I don’t have a clue how you would write a unit test for the above scenario – at least not if all we’re dealing with is simple HTML pages. Frameworks such as Zend for PHP and ASP.NET MVC for C# lend themselves to such cases, which is one reason why they’re so popular. Here’s how we might do it in C#:

Of course, the implementation of such a test will vary greatly depending on the framework. Arrange-Act-Assert is a common pattern for unit testing:

Arrange: Set up any variables that will be used in the test

Act: Call the method or execute the action to be tested

Assert: Check that the conditions of the test were met

At the end of the TestLinks method above, we assert that the number of errors is equal to zero. If it’s not, then the test will fail, letting us know that a link is broken. Ideally, you would run this test after making any changes that could affect it. Most importantly, you would run it before committing those changes to source control.

Dependency injection

Dependency injection is often associated with unit testing because it allows you to test a unit of code by passing in a fake implementation rather than a concrete object. The most obvious case where you would want use this is to test a unit of code that needs to save data to a database.

Imagine that, on your website, a user can sign up for an account. To do this, the user must fill out and submit a form, which inserts a record into the database. This is something that needs to be tested – extensively, in fact, if you are a good developer.

If you’re using a data layer such as NHibernate or Entity Framework, you don’t need to test that the data is inserted into the database correctly. Also, you don’t want to insert a bunch of dummy data into the database. Instead, you need to test that the form is submitted, that an account is created, and that the page is redirected. If the user forgets to fill out a required field on the form, the page should be redirected to an error page, or back to the same page so the user can try again.

Now, assume your user controller has an action called NewUser that handles the form submission. In ASP.NET MVC, it might look something like this:

Running that test would insert the dummy data into the database, but we’re not interested in that part. What we’d rather do is skip that part and just test that the page is redirected to the right action. To do that, we need to pass a fake database to the home controller:

Then, we would need to modify the constructor of our user controller to accept a parameter for the repository. In other words, we need to inject our dependency into the constructor. We also remove the instantiation of the database class from the NewUser action:

Instead of saving the data, our fake implementation of the database class just pretends to save the data so we can go on testing the parts we care about.

Conclusion

Hopefully, now you get the basic ideas behind unit testing and dependency injection. As I mentioned before, my next article will cover using NUnit and Moq for unit testing an ASP.NET MVC 3 application with NHibernate and Castle Windsor already implemented.

The title of this article is so long, I briefly considered using an acronym. Unfortunately, FNHAMASPDNMVC3CW doesn’t communicate much except to the nerdiest of nerds.

This is the third article in a series on using Fluent NHibernate with auto mappings. The first one demonstrated its basic functionality in a console application, and the second one showed how to convert the first one into an ASP.NET MVC 3 application. This article will cover how to use Castle Windsor for dependency injection, which is important for unit testing. I won’t include any unit tests in this article, but will lay the foundation that will make unit testing possible for my next article.

Once again, create a new ASP.NET MVC 3 web application in Microsoft Visual Studio 2010 and use the empty project template. This time, call your project CastleFluentNHibernateMvc3. Next, right click on the project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for Fluent NHibernate and install it. We also need Castle Windsor, so search for that and install it too.

Once you’ve installed the packages, copy the Controllers, Models and Repositories folders from our previous project to our new project. Also, copy the Views/Home folder to our new project. Make sure you change the namespace in each file accordingly.

The first thing we need is a Windsor controller factory. The Windsor controller factory overrides two methods of the default MVC controller factory and is central to how Castle Windsor resolves controller dependencies. Create this class in a new Windsor directory at the root level of the project:

Next, we need to tell MVC to use the Windsor controller factory instead of the default one. To do that, we’ll add a couple of methods to the MvcApplication class, which resides in the Global.asax.cs file at the root of the project:

Now, we need to tell Windsor about our controllers, including where they reside and how to configure them. In other words, we’ll “register” our controllers with the Windsor “container.” We do this using an “installer.” Create this class in your Windsor directory:

Next, create a new class named PersistenceFacility in your Windsor directory, and move the CreateSessionFactory, CreateDbConfig, CreateMappings and UpdateSchema methods of our NHibernateSessionPerRequest class there:

In the Init method, we’re telling Castle Windsor what to do when it encounters a dependency on ISessionFactory or ISession. If we ask for an ISession, it will resolve the dependency using the OpenSession method. Notice that this method needs an ISessionFactory, which Castle Windsor will resolve by calling CreateSessionFactory.

We’re also telling Castle Windsor that an ISession instance should be bound to a web request. Since we aren’t specifying a lifestyle for ISessionFactory, the default value of singleton will be used. In other words, only one session factory will be instantiated during the lifetime of our app, and it will hang around in memory until our app dies. This is basically the same thing we did before with our custom HTTP module, except the dependencies will only be resolved when needed. We can verify this by placing breakpoints in the OpenSession and CreateSessionFactory methods and running the app.

Now, we need to register our persistence facility with the Windsor container. Again, we do this using an installer. Create this class in your Windsor directory:

Next, we need to add a few more methods to our repository in order to manage NHibernate transactions: BeginTransaction, Commit and Rollback. Previously, we created a custom HTTP module to take care of these operations at the beginning and end of each web request. This time, we’ll manage each transaction ourselves, gaining more control and performance in the process. The GetAll, Get, SaveOrUpdateAll and SaveOrUpdate methods will stay the same:

Notice that the repository constructor has been modified to accept an argument of type ISession. This is called dependency injection, and its benefits will become more clear when we use it in our home controller.

But first, we need to register our repositories with the Windsor container. How do we do that? Right! (You did say “use an installer,” right? Good.) Create this class in your Windsor directory:

The benefit of using dependency injection here is that we no longer have a dependency on a concrete repository. The home controller doesn’t care what the repository does with our data, as long as it implements IRepository. This way, we can change our repository methods without changing our controller actions. Later, when we write unit tests for our controller actions, we’ll be able to create an instance of the home controller using a fake repository so that our tests don’t touch our data.

Because we are no longer using a custom HTTP module to manage NHibernate transactions, we need to call the BeginTransaction method of our repository whenever we get data from or save data to the database. We also need to call the Commit method to flush the NHibernate session, and call the Rollback method if any errors occur:

You can now run your application. If you get any errors, make sure you have an empty database and a valid connection string. In that case, see my previous article for instructions on setting that up. If all you see is the word “Index,” it’s because you don’t have any data in your database yet. In your browser, navigate to the Seed action of the home controller. You should then see “Index” at the top followed by a list of stores, products and employees.

Next time, we’ll look as using NUnit and Moq for unit testing. Surprisingly, it’s relatively easy! As always, let me know if you have any difficulties. Good luck!

In my previous article, I demonstrated how to use Fluent NHibernate with auto mappings. After that, my plan was to move the code into an ASP.NET MVC 3 application. I assumed it would be relatively simple, which goes to show just how little I know about these things. Anyways, hopefully someone else out there will be able to learn from my experience.

Here’s what the completed project will look like:

Create a new ASP.NET MVC 3 web application called FluentNHibernateMvc3 in Microsoft Visual Studio 2010 and use the empty project template. Next, right click on the project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for Fluent NHibernate and install it.

Once you’ve installed Fluent NHibernate, copy the Employee, Product and Store classes from the Entities folder of our previous project to the Models folder of our current project. Make sure you change the namespace in each file accordingly.

Next, create a new controller called HomeController in the Controllers folder. Since my goal is to move the code from our previous project to our new project with as little changes as possible, the HomeController class will look very similar to the Program class with the following exceptions:

We’ll move the NHibernate specific methods to a new custom HTTP module.

We’ll use a repository to create a layer of abstraction between our main application and our persistence layer.

We’ll split the Main method into two actions: the Index action, which will display the data, and the Seed action, which will add sample data to our database. This is because we don’t want to add sample data every time our application runs.

We don’t create a new session factory in the Seed action, or anywhere else in the home controller for that matter.

We don’t open a session here.

We don’t create or commit a transaction.

These tasks will be handled by our custom HTTP module at the beginning and end of each web request. Separating these tasks allows us to minimize the dependencies in our home controller, which is often referred to as loose coupling. Our controller doesn’t know anything about sessions or transactions – it isn’t even aware of NHibernate!

Now, let’s tackle that repository. Place these files in a new folder called Repositories at the root level of the project. This is where we’ll define what exactly the GetAll and SaveOrUpdateAll methods do that we’re using in our controller actions. First, create the interface:

Speaking of loose coupling, our repository doesn’t know anything about session factories or transactions, but it does have a session field that implements ISession. This field is set by calling the GetCurrentSession method of our custom HTTP module, which we’ll name NHibernateSessionPerRequest.

Here’s an outline of the NHibernateSessionPerRequest class, which you can put in a new Modules folder at the root level of the project:

Notice that the sessionFactory field, which implements ISessionFactory, is static. Session factories can be expensive to create, especially with a large domain model. So we only want to instantiate one of these during the lifetime of our app, which will hang around in memory until our app dies:

Most of these methods can be copied to this class from our previous project. There are only a few changes:

We’ve replaced the DropCreateSchema method with a new method called UpdateSchema. As the name suggests, this method will only create the database schema if it doesn’t already exist. Otherwise, it will update it from the model.

NHibernate needs to be told what type of context it’s running in. We do that by calling the CurrentSessionContext extension method in our fluent configuration. It’s strongly typed, so we give it a type of WebSessionContext.

Instead of building a connection string in the CreateDbConfig method, I’m using a connection string from the Web.config file. You can do it either way.

The CreateMappings method will create auto mappings for all types in our assembly that have a namespace ending in “Models”. This is preferable over matching the entire namespace, since it will require less changes moving forward.

Previously, we weren’t catching any exceptions when we tried to commit our transaction. Wrapping our call to commit in a try-catch statement gives us a chance to rollback if something goes wrong.

We’re almost done! We still need to register our custom HTTP module in IIS, so that it can receive and process HTTP requests. If you are using IIS 6.0 or IIS 7.0 in classic mode, add this to your Web.config file:

Finally, if you decided not to build a connection string in the CreateDbConfig method, you’ll need to add one under the configuration section of your Web.config file. Here’s mine, which is using SQL Server 2008:

Before running the application, make sure you create an empty database, and replace “testServer”, “testDB”, “testUser” and “testPass” with your actual server, database, username, and password.

When you run the application, you should see this:

Index

Not very exciting, it is? That’s because we haven’t added any data to the database yet! In your browser, navigate to the Seed action of the home controller, i.e. append /Home/Seed to the URL in your browser’s address bar. You should see this:

This action is fairly self-explanatory: It will find the Store record named “Bargin Basin” and rename it to “Bargain Basin.” The cool part is that we don’t have to manually save anything because it’s all taken care of by our repository and HTTP module! Navigate to the Test action of the home controller in your browser and you’ll see what I mean.

That does it for this article. Next time, I’ll cover unit testing and dependency injecting using Castle Windsor.

To begin, create a new console application called FluentNHibernateConsole in Microsoft Visual Studio 2010. Next, right click on the project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for Fluent NHibernate and install it.

Before Fluent NHibernate version 1.3.0.717, we could make the setter function of the Id property private instead of protected. The reason it needs to be one or the other is because it should never be changed by the code. Instead, it should only ever be touched by NHibernate.

Not only should the Id property of the Product class be protected, but the StoresStockedIn property should be as well. Once this list is populated, we should never be able to set it since that would create orphaned Store records.

Before running the application, make sure you create an empty database, and replace “testServer”, “testDB”, “testUser” and “testPass” with your actual server, database, username, and password. Note that I’m using SQL Server 2008, but you can use SQLite, MySQL, or any other supported database. You can also read the connection string from a settings file, which you can read more about on the Fluent NHibernate Wiki.

Next, we configure our mappings with a call to the CreateMappings method:

Normally, NHibernate uses XML files to determine how each entity in the domain model relates to each table in the database. Fluent NHibernate allows us to bypass this laborious step with auto mappings. We can add other conventions here, but all we need to get our application running is to turn cascading on. This way, when we save a Store, all the associated Products and Employees are saved too.

Next, we tell NHibernate to drop and create our database schema each time the application runs:

This step is optional. If you prefer, you can the database schema manually. You can also tell NHibernate to update the schema only when the model changes:

// Updates the database schema if there are any changes to the model
private static void UpdateSchema( Configuration cfg )
{
new SchemaUpdate( cfg );
}

Finally, we build the session factory. This is the last step in our fluent configuration.

We can now run the application. When you do so, you should see this:

If this is what you see, then congratulations on completing your first Fluent NHibernate project with auto mappings! If not, drop me a comment and we’ll try to get it figured out. I’m pretty new to this too, so don’t be afraid to ask!