Archive

Archive for the ‘.Net’ Category

NHibernate presentations at DNUG Bern

September 2nd, 2010 Patrick No comments

dnugbe

I hold in August two presentations at the .Net User Group Bern together with René Leupold.  In both presentations the topic was object relational mapping in the .Net world. So we showed Microsoft Entity Framework 4.0 and NHibernate. My part was NHibernate and Rene showed EF.

In the first presentation which was on 16th August 2010, we presented the following stuff:

  • Introduction into ORM
  • Theory (ORM impedance mismatch, persistence ignorance and ORM isn’t a silver bullet)
  • Approaches how to map entities (top down, middle out, bottom up and meet in the middle)
  • Introduction into Entity framework (history, vote of no confidence, supported approaches)
  • Short demo of Entity framework (configuration, hello world sample)
  • Introduction into NHibernate (history, multiple options to do things, supported approaches)
  • Short demo of NHibernate (configuration, hello world sample)
  • Mappings and short demos of them (1:m, m:n, 1:1, self references, 1 class and multiple tables, 1 table and multiple classes, inheritance with TPH, TPT and TPC)

You can find the slides here.

In the second presentation which was on 23th August 2010, we presented the following topics:

  • Queries (I showed HQL, Criteria API with QBC and QBE, NativeSQL, Named Queries and QueryOver in NHibernate 3.0)
  • Lazy and Eager Loading
  • Debugging and Profiling (also with NHProf from Ayende)
  • Optimizations

We had more stuff for the second session like Concurrency, Auditing, Validation and Caching, but we hadn’t the time to show all these things. You can find the slides from the second session here.

The samples of both sessions are also available. If you use them commercially or for other public activities, please mention the authors (NHibernate: Patrick Weibel, EF: René Leupold). The samples for NHibernate could be found here and those for EF you find here.

  • Share/Bookmark
Categories: .Net, Private Tags:

ConfORM – Another NHibernate mapping possibility

September 1st, 2010 Patrick 2 comments

I recently hold two presentations at the .Net User Group Bern (DNUG) with René Leupold about object relational mapping in the .Net world. We showed Entity Framework 4.0 and NHibernate. My part was NHibernate. You could download the slides and samples from the DNUG website.

In the two presentations I showed the mapping possibilities with hbm.xml files, attributes and Fluent NHibernate. In a previous blog post I already showed those possibilities.ConfOrmBigTransparent

During the preparations I hadn’t time to try a new way to map your entities to the database. This new way is offered by the framework ConfORM, created by one of the contributors of NHibernate Fabio Maulo.

In a previous post I showed the other possibilities how you can map your entities. In this post I show you the most simplest way I found to map the entities with ConfORM. I used for this example the version 1.0.2 (Alpha 2) of ConfORM and the version 3.0.0 Alpha 2 of NHibernate. The current version of ConfORM is available here.

Domain

The domain for this sample is quite simple. It is a one to many mapping between Order and its OrderItems. The associations is bidirectional. Below you see the class diagram of the two classes:

ClassDiagram

Database

The following ERD show the two tables Order and OrderItem in the database. Between the two tables exists a foreign key constraint. None of the fields are nullable.

database

Configuration

First, we need to declare the connection string, so that we could connect to the database. I could do it in the code, but even for a such simple example it is too dirty for me. So I added an application configuration file (app.config) and added following lines:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<connectionStrings>
		<add name="default" connectionString="Server=localhost;database=ORMSamples;Integrated Security=SSPI;"/>
	</connectionStrings>
</configuration>

Now I have a connectionstring named “default” which points to my local database ORMSamples.

When you are familiar with NHibernate, you know that you have to have a place where your session factory lives and will be created. For this purpose I normally create a class called PersistenceManager. The field factory, the property Factory and the method OpenSession are the code I would create also when I map my entities with hbm.xml files or with Fluent NHibernate or with attributes.

Where it starts to be different is the CreateConfiguration method. In this method I could create the configuration part by code. This fluent API to create a configuration is called Loquacious. Normally I would declare all this stuff in the application configuration file.

I think for a such simple application it is OK to do it like that, but I prefer the way over the application configuration file. The reason for that is, that I could configure my application for each scenario (depends on database product, etc.).

namespace ORMSamples.ConfORM.Utils
{
	public class PersistenceManager
	{
		private static ISessionFactory factory;

		private static ISessionFactory Factory
		{
			get
			{
				if(factory == null)
				{
					Configuration config = CreateConfiguration();
					factory = config.BuildSessionFactory();
				}

				return factory;
			}
		}

		public static ISession OpenSession()
		{
			return Factory.OpenSession();
		}

		private static Configuration CreateConfiguration()
		{
			var configure = new Configuration();
			configure.SessionFactoryName("Demo");

			configure.Proxy(p => p.ProxyFactoryFactory<ProxyFactoryFactory>());
			configure.DataBaseIntegration(db =>
			{
				db.Dialect<MsSql2008Dialect>();
				db.Driver<SqlClientDriver>();
				db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
				db.ConnectionString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
				db.LogSqlInConsole = true;
				db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'";
			});

			configure.AddDeserializedMapping(GetMapping(), "ORMSamples_ConfORM");

			return configure;
		}

		private static HbmMapping GetMapping()
		{
			return null;
		}
	}
}

Yet I didn’t map one entity but there is an empty method GetMapping. In this method we will program our mapping in the next section.

Mapping

Below you see the completed class PersistenceManager. The implementation was created based on the example in the source code of ConfORM. The main method here is the GetMapping method. It implements a template method pattern to create the mapping.

Very important for the mapping is the method DomainDefinition. There you define your domain what means you declare all root entities. In our case it means that we have to add Order and OrderItem as root entities. For this purpose you have to call TablePerClass on the instance of the ObjectRelationalMapper class for each entity (or call it once for a collection of entities).

The patterns in ConfORM I will leave here out and come directly to the Customize method. In this method I implemented again a template method pattern. In the method CustomizeRelations I define all specialties of my entities, in the method CustomizeTables I define the DB-Schemas and finally in the method CustomizeColumns I define that the properties are all not nullable.

namespace ORMSamples.ConfORM.Utils
{
	public class PersistenceManager
	{
		private static ISessionFactory factory;

		private static ISessionFactory Factory {...}

		public static ISession OpenSession() {...}

		private static Configuration CreateConfiguration() {...}

		private static HbmMapping GetMapping()
		{
			ObjectRelationalMapper orm = new ObjectRelationalMapper();
			orm.Patterns.PoidStrategies.Add(new NativePoidPattern());
			Mapper mapper = new Mapper(orm);

			var entities = new List<Type>();

			DomainDefinition(orm);
			RegisterPatterns(mapper, orm);
			Customize(mapper);

			entities.AddRange(GetEntities());

			return mapper.CompileMappingFor(entities);
		}

		private static void DomainDefinition(ObjectRelationalMapper orm)
		{
			orm.TablePerClass(GetEntities());
		}

		private static void RegisterPatterns(Mapper mapper, IDomainInspector domainInspector)
		{
		}

		private static void Customize(Mapper mapper)
		{
			CustomizeRelations(mapper);
			CustomizeTables(mapper);
			CustomizeColumns(mapper);
		}

		private static void CustomizeRelations(Mapper mapper)
		{
			mapper.Class<Order>(cm =>
			{
				cm.Id(o => o.Id, im => im.Generator(Generators.Identity));
				cm.Bag(
					o => o.Items,
					x =>
						{
							x.Key(k => k.Column("OrderId"));
							x.Lazy(CollectionLazy.NoLazy);
						},
					x => { });
			});
			mapper.Class<OrderItem>(cm =>
			{
				cm.Id(o => o.Id, im => im.Generator(Generators.Identity));
				cm.ManyToOne(
					x => x.Order,
					m =>
						{
							m.Column("OrderId");
							m.Fetch(FetchMode.Join);
							m.NotNullable(true);
						});
			});
		}

		private static void CustomizeTables(Mapper mapper)
		{
			mapper.Class<Order>(cm => cm.Schema("OneToMany"));
			mapper.Class<OrderItem>(cm => cm.Schema("OneToMany"));
		}

		private static void CustomizeColumns(Mapper mapper)
		{
			mapper.Class<Order>(
				cm =>
					{
						cm.Property(x => x.OrderNumber, m => m.NotNullable(true));
						cm.Property(x => x.CompanyName, m => m.NotNullable(true));
						cm.Property(x => x.Street, m => m.NotNullable(true));
						cm.Property(x => x.PostalCode, m => m.NotNullable(true));
						cm.Property(x => x.City, m => m.NotNullable(true));
					});
			mapper.Class<OrderItem>(
				cm =>
				{
					cm.Property(x => x.Quantity, m => m.NotNullable(true));
					cm.Property(x => x.ProductId, m => m.NotNullable(true));
				});
		}

		private static IEnumerable<Type> GetEntities()
		{
			return typeof(Order).Assembly.GetTypes().Where(t => t.Namespace == typeof(Order).Namespace);
		}
	}
}

How to test it

Normally I would start with the test first, but this post is about ConfORM and not about TDD or the test first approach. To test our simple example is quite easy: You could create some CRUD-Tests. To not clutter this blog post I publish here just a Create-Test. As you can see, it’s normal NHibernate code and the whole mapping is encapsulated in the PersistenceManager class.

namespace ORMSamples.ConfORM.Test.OneToMany
{
	[TestFixture]
	public class OneToManyCRUDTest
	{
		private Order order;
		private OrderItem orderitem;

		[SetUp]
		public void SetUp()
		{
			order = new Order();
			orderitem = new OrderItem();
		}

		[TearDown]
		public void TearDown()
		{
			using(ISession session = PersistenceManager.OpenSession())
			using(ITransaction tx = session.BeginTransaction())
			{
				session.Delete(order);
				tx.Commit();
			}
		}

		[Test]
		public void TestCreate()
		{
			// Arrange
			order.OrderNumber = "12345";
			order.CompanyName = "Test Company";
			order.Street = "Hauptstrasse 1";
			order.PostalCode = "1234";
			order.City = "Zürich";
			orderitem.Order = order;
			order.Items.Add(orderitem);
			orderitem.ProductId = 234;
			orderitem.Quantity = 1;

			// Act
			using(ISession session = PersistenceManager.OpenSession())
			using(ITransaction tx = session.BeginTransaction())
			{
				session.Save(order);
				tx.Commit();
			}

			// Assert
			Assert.AreNotEqual(0, order.Id);
			Assert.AreNotEqual(0, orderitem.Id);
		}
	}
}

Conclusion

The first impression of ConfORM was that it seemed to me more complicated than Fluent NHibernate. But after a while I was able to work with. I’m sure, that I didn’t understand all implemented ideas, but the framework still in alpha so I have time to learn them.

ConfORM doesn’t say you how to manage the code where you specify your mappings like Fluent NHibernate. So, you have to be cautious not to code all your mappings in one class (as I did with the PersistenceManager). In this point I find the more stricter way of Fluent NHibernate a bit better.

The owner and contributor of ConfORM, Fabio Maulo, has react very fast as I asked him to implement the missing fetch attribute for collections. If you have questions about ConfORM, you can ask him directly via twitter or the community via the Google user group. ConfORM is definitively an interesting alternative for mapping entities in a fluent way.

  • Share/Bookmark

Mocking frameworks in .Net

March 30th, 2010 Patrick 6 comments

A few month ago I played with some mocking frameworks in .Net. There are already some comparisons available (here, here or here). In this blog post I want to show which frameworks are available and which one fits best for agile development.

You could download the source code from github.com.

Software under Test (SUT)

To demonstrate and evaluate all the different mocking framework I had to create a scenario where it is appropriate to use a mocking framework. So I chose an user entity which I want to validate and in a successful case also to persist in a database.

namespace Mocking
{
	public class User
	{
		public IUserGateway Gateway
		{
			get; set;
		}

		public User()
		{
			this.Gateway = new UserGateway();
		}

		public User(IUserGateway gateway)
		{
			this.Gateway = gateway;
		}

		public bool Persist(IUserValidator validator)
		{
			bool bValid = validator.Validate(this);

			if(bValid) bValid = this.Gateway.Persist(this);

			return bValid;
		}
	}
}

This is the User entity class which implements the active record pattern. As you see, there are three injection patterns realized, the constructor injection and setter injection for the gateway and the parameter injection for the validator.

namespace Mocking
{
	public class UserGateway : IUserGateway
	{
		public virtual bool Persist(User user)
		{
			return true;
		}
	}
}

The UserGateway class is responsible to persist the entity. In my scenario it is just a dummy, because I don’t want to setup a database for this demo.

namespace Mocking
{
	public class UserValidator : IUserValidator
	{
		public bool Validate(User user)
		{
			if(user == null) return false;

			return true;
		}
	}
}

The validator is also more or less just a dummy for this demo.

Both interfaces, IUserGateway and IUserValidator, has the same methods, properties as the classes which implement them.

NMock2

One of the first mocking frameworks in .Net which I was looking at was NMock2. Specially the cheat sheet make it really easy to learn this framework.

namespace MockingTest
{
	[TestClass]
	public class NMock2Test
	{
		[TestMethod]
		public void TestPersist()
		{
			Mockery mocks = new Mockery();

			//Create mocks
			IUserGateway mockGateway = mocks.NewMock<IUserGateway>();
			IUserValidator mockValidator = mocks.NewMock<IUserValidator>();

			//Create user
			User user = new User();

			//Expectations
			using(mocks.Ordered)
			{
				Expect.Once.On(mockValidator).Method("Validate").With(user).
Will(Return.Value(true));
				Expect.Once.On(mockGateway).Method("Persist").With(user).
Will(Return.Value(true));
			}

			//Assign Gateway
			user.Gateway = mockGateway;

			//Test method
			Assert.AreEqual(true, user.Persist(mockValidator));

			mocks.VerifyAllExpectationsHaveBeenMet();
		}
	}
}

You could use the AAA-Syntax (Arrange-Act-Assert). Also more extended features like the ordered calls with the using syntax is very nice.

But, there is are also negative points: NMock2 uses “magic strings”. In your Expectations you have to declare the called method with a strings, which makes your tests very brittle when your refactor your code. For example if you have to rename a method, even the compiler could not help you. An other negative point is, that you can only mock interfaces. When you have to mock a class, you have to change your design by adding an interface just for mocking.

NMock3

Recently I discover, that there is already a follower of NMock2 on codeplex: NMock3.

namespace NMock3Test
{
    [TestClass]
    public class NMock3Test
    {
        [TestMethod]
        public void TestPersist()
        {
            MockFactory factory = new MockFactory();

            //Create mocks
            Mock<IUserGateway> mockGateway = factory.CreateMock<IUserGateway>();
            Mock<IUserValidator> mockValidator = factory.CreateMock<IUserValidator>();

            //Create user
            User user = new User();

            //Expectations
            using(factory.Ordered)
            {
                mockValidator.Expects.One.MethodWith(m => m.Validate(user)).WillReturn(true);
                mockGateway.Expects.One.MethodWith(m => m.Persist(user)).WillReturn(true);
            }

            //Assign gateway
            user.Gateway = mockGateway.MockObject;

            //Test method
            Assert.AreEqual(true, user.Persist(mockValidator.MockObject));

            factory.VerifyAllExpectationsHaveBeenMet();
        }
    }
}

The migration is quite easy: Replace the reference from your test project from the NMock2.dll with a new reference to the NMock3.dll. After that you could use the new approach with the MockFactory and the lambda expressions in your Expectations.

NMock3 introduce type safety and readiness for refactorings combined with the easiness of NMock2. They also keep the tradition of a good cheat sheet.

With NMock3 I couldn’t mock a class (even when I followed the exceptions…"). The creation of stubs should be possible. The project is still a young one and so the documentation isn’t that good as it should be. But NMock3 remain an interesting mocking framework.

Simple.Mocking

When I looked for mocking frameworks I also found this new and not very well known framework Simple.Mocking on codeplex. Its also avoid “magic strings” and you could also use the AAA-Syntax. Simple.Mocking has only one committer, Mikael Waltersson.

namespace MockingTest
{
    [TestClass]
    public class SimpleNetTest
    {
        [TestMethod]
        public void TestPersist()
        {
            //Create mocks
            var expectationScope = new ExpectationScope();
            IUserGateway mockGateway = Mock.Interface<IUserGateway>(expectationScope);
            IUserValidator mockValidator = Mock.Interface<IUserValidator>(expectationScope);

            //Create user
            User user = new User();

            //Expectations
            Expect.Once.MethodCall(() => mockValidator.Validate(user)).Returns(true);
            Expect.Once.MethodCall(() => mockGateway.Persist(user)).Returns(true);

            //Assign gateway
            user.Gateway = mockGateway;

            //Test method
            Assert.AreEqual(true, user.Persist(mockValidator));

            AssertExpectations.IsMetFor(expectationScope);
        }
    }
}

The ExpectationsScope is used to avoid to call AssertExpectations.IsMetFor for each mock. This construct is special and I’m (currently) not a big fan of it.

With Simple.Mocking you could just mocking interfaces and delegates, you couldn’t mock classes.

Rhino.Mocks

Rhino.Mocks is one of the famous .Net mocking frameworks. As Simple.Mocking there is also only one committer to this framework, Oren Eini (alias Ayende Rahien).

namespace MockingTest
{
	[TestClass]
	public class RhinoMockTest
	{
		[TestMethod]
		public void TestPersistWithRecordingReplay()
		{
			MockRepository mocks = new MockRepository();

			IUserGateway gateway = mocks.StrictMock<IUserGateway>();
			IUserValidator validator = mocks.StrictMock<IUserValidator>();

			//Create user
			User user = new User();

			//Expectations
			using(mocks.Ordered())
			{
				Expect.Call(validator.Validate(user)).Return(true);
				Expect.Call(gateway.Persist(user)).Return(true);
			}

			//Stop recording, start replay
			mocks.ReplayAll();

			//Assign gateway
			user.Gateway = gateway;

			//Test method
			Assert.AreEqual(true, user.Persist(validator));

			mocks.VerifyAll();
		}

		[TestMethod]
		public void TestPersistWithArrangeActAssert()
		{
			var gateway = MockRepository.GenerateMock<IUserGateway>();
			var validator = MockRepository.GenerateMock<IUserValidator>();

			//Create user
			User user = new User();

			//Expectations
			validator.Expect(x => x.Validate(user)).Return(true);
			gateway.Expect(x => x.Persist(user)).Return(true);

			//Assign gateway
			user.Gateway = gateway;

			//Test method
			Assert.AreEqual(true, user.Persist(validator));

			//Asserts
			validator.VerifyAllExpectations();
			gateway.VerifyAllExpectations();
		}
	}
}

Rhino.Mocks supports two ways to use the framework: the record-replay and the AAA-syntax. My favorite is clearly the AAA-syntax, because there is much less code needed (reduced accidental complexity). Rhino.Mocks uses also Lambda-Expressions to avoid “magic strings”, so refactoring shouldn’t be a problem.

Moq

Moq is another mocking framework which takes advantage of the .Net 3.0 language features like lambda expressions. So Moq doesn’t use “magic strings” and it enables also the AAA-syntax. There are two ways how to create mocks. You could create mocks directly with the Mock class or you could use the MockFactory class. For both scenarios I created a test.

namespace MockingTest
{
	[TestClass]
	public class MoqTest
	{
		[TestMethod]
		public void TestPersist()
		{
			var gateway = new Mock<IUserGateway>();
			var validator = new Mock<IUserValidator>();

			User user = new User();

			//Expectations
			validator.Setup(x => x.Validate(user)).Returns(true).AtMostOnce();
			gateway.Setup(x => x.Persist(user)).Returns(true).AtMostOnce();

			//Assign gateway
			user.Gateway = gateway.Object;

			//Test method
			Assert.AreEqual(true, user.Persist(validator.Object));

			validator.VerifyAll();
			gateway.VerifyAll();
		}

		[TestMethod]
		public void TestPersistWithFactory()
		{
			MockFactory factory = new MockFactory(MockBehavior.Strict);

			//Class works, but methods have to be virtual -> not nice
			var mockGateway = factory.Create<UserGateway>();
			var mockValidator = factory.Create<IUserValidator>();

			User user = new User();

			//Expectations
			mockValidator.Setup(x => x.Validate(user)).Returns(true).AtMostOnce();
			mockGateway.Setup(x => x.Persist(user)).Returns(true).AtMostOnce();

			//Assign gateway
			user.Gateway = mockGateway.Object;

			//Test method
			Assert.AreEqual(true, user.Persist(mockValidator.Object));

			factory.VerifyAll();
		}
	}
}

I prefer the MockFactory approach, because you don’t need to verify each mock (its reduce the test code which is a good thing). Be sure, that in this scenario you don’t forget the parameter MockBehavior.Strict which makes your mock objects real mocks. Without this parameter they are more like Stubs, which don’t fail and just return a default value.

But there is a little problem: If you want to mock a class, then all the methods have to be virtual, but Moq has no problem to mock an interface.

Typemock Isolator

Unfortunately Typemock Isolator isn’t free, but you could get a trial to try this great mocking framework. As you could see in the TestPersistWithReflectiveMocking Typemock Isolator could mock classes, also non-virtual methods. Great. It also doesn’t use “magic strings”. But wait, you could not mock interfaces? With the new AAA-syntax it is possible and it looks very nice.

namespace MockingTest
{
	[TestClass]
	public class TypeMockTest
	{
	    [TestMethod]
	    public void TestPersistWithNaturalMocking()
	    {
	        MockManager.Init();

	        User user = new User();

	        // Natural mocking
	        using(RecordExpectations recorder = new RecordExpectations())
	        {
	            IUserGateway mockGateway = new UserGateway();
	            IUserValidator mockValidator = new UserValidator();

	            //Expectations
	            recorder.ExpectAndReturn(mockValidator.Validate(user), true);
	            recorder.ExpectAndReturn(mockGateway.Persist(user), true);
	        }

	        //Create instances
	        IUserGateway gateway = new UserGateway();
	        IUserValidator validator = new UserValidator();

	        //Assign gateway
	        user.Gateway = gateway;

	        //Method
	        Assert.AreEqual(true, user.Persist(validator));

	        MockManager.Verify();
	    }

	    [TestMethod]
	    public void TestPersistWithReflectiveMocking()
	    {
	        MockManager.Init();

	        //Create mocks
	        Mock mockGateway = MockManager.Mock<UserGateway>();
	        Mock mockValidator = MockManager.Mock<UserValidator>();

	        //Create user
	        UserGateway gateway = new UserGateway();
	        IUserValidator validator = new UserValidator();
	        User user = new User(gateway);

	        //Expectations
	        mockValidator.ExpectAndReturn("Validate", true).Args(user);
	        mockGateway.ExpectAndReturn("Persist", true).Args(user);

	        //Method
	        Assert.AreEqual(true, user.Persist(validator));

	        MockManager.Verify();
	    }

		[TestMethod]
		[Isolated]
		public void TestPersistWithAAA()
		{
			//Arrange
			//Create mocks
			UserGateway gateway = Isolate.Fake.Instance<UserGateway>();
			IUserValidator validator = Isolate.Fake.Instance<IUserValidator>();
            //Create user
			User user = new User(gateway);
            //Expectations
			Isolate.WhenCalled(() => validator.Validate(user)).WillReturn(true);
			Isolate.WhenCalled(() => gateway.Persist(user)).WillReturn(true);

			//Act
			bool bPersist = user.Persist(validator);

			//Assert
			Assert.AreEqual(true, bPersist);
		}
	}
}

Typemock Isolator also supports the record-replay approach (demonstrated in the TestPersistWithNaturalMocking test method). But as you already know, I prefer the AAA-syntax.

The question about Typemock Isolator is, if it is worth to pay for a mocking framework if there are so much other free opportunities?  Typemock Isolator is very powerful and for some companies it is very important to get support and also guarantee that the product will be continued for example ten years. In such a scenario Typemock Isolator would be definitely an option. In reaction of such scenarios, also other providers of mocking frameworks offer commercial support for their frameworks, for example Rhino.Mocks.

The undocumented – NUnit Mocking

It is not very known that there exists also in NUnit a mocking framework. It is possible to mock interfaces and classes if the inherit from MarshalByRefObject.

namespace MockingTest
{
	[TestClass]
	public class NUnitMockTest
	{
		[TestMethod]
		public void TestPersist()
		{
			//Gateway
			DynamicMock mockGateway = new DynamicMock(typeof(IUserGateway));
			IUserGateway gateway = (IUserGateway) mockGateway.MockInstance;

			//Validator
			DynamicMock mockValidator = new DynamicMock(typeof(IUserValidator));
			IUserValidator validator = (IUserValidator)mockValidator.MockInstance;

			//User
			User user = new User(gateway);

			//Expectations
			mockValidator.ExpectAndReturn("Validate", true, user);
			mockGateway.ExpectAndReturn("Persist", true, user);

			Assert.AreEqual(true, user.Persist(validator));
			mockValidator.Verify();
			mockGateway.Verify();
		}
	}
}

The mocking framework is easy to use and if you already use NUnit, then you don’t need an additional framework.

As I know, it isn’t official and there is no documentation. You have also to use “magic strings” for methods and the limitation for classes also reduce the benefit.

Conclusion

For a modern mocking framework it is essential that its enable refactoring by not using “magic strings”. It is also essential for me that it allows to use the AAA-syntax. A third essential thing is that it allows you to mock classes. You don’t want to create interface just for mocking, for example for your domain model. Avoid accidental complexity is very important, so you shouldn’t add unnecessary code just for mocking. That doesn’t mean that “design for testability” is wrong, “design for testability” means, that you design your code in a way, that you have the possibility to test your code, for example you avoid huge classes (god object anti-pattern) with a lot of private methods or you avoid creation of instances in methods (unable to use dependency injection).

So, which framework fulfill all the requirements? NMock3, which inherit the easiness of NMock2 combined with the elimination of the “magic strings”? Or Typemock Isolator which also eliminate the “magic strings” and could even mock classes?

For me, there isn’t currently a clear winner visible, maybe Typemock makes the race. But there are frameworks which I would no longer use, as NMock2 or NUnit mocking. They don’t fulfill my requirements clearly. That doesn’t mean they aren’t suitable for your scenarios.

Also to be clear: There are other topics that should be considered: mocking events, Stubs, etc. The list of the mocking frameworks isn’t complete, for example Moles is a framework which could be interesting too.

  • Share/Bookmark
Categories: .Net, Best practices, Testing Tags:

Favoured podcasts

November 1st, 2009 Patrick 2 comments

I migrated my desktop PC to Windows 7 Professional. I didn’t choose the upgrade path, I install Windows 7 from scratch. So, after installing iTunes I had to register my favoured podcasts again:

.Net

Java

Currently I work in a .Net environment, so the list of .Net podcasts is a bit longer. If you are interested in more Java podcasts, there is a question about that topic on Stackoverflow. The following three podcasts are definitely interesting:

Do you have other interesting podcasts?

  • Share/Bookmark
Categories: .Net, Java, Private, Software engineering Tags:

NHibernate mapping possibilities

August 24th, 2009 Patrick 1 comment

I prepare currently a new talk about NHibernate. In this talk I’ll show the different mapping possibilities with NHibernate. To demonstrate the three possibilities (and a fourth one) I chose a quite simple model: I implement three classes Cat, Dog and Bird an for each one I chose a different mapping approach. For my little sample application I used NHibernate 2.1.0, NHibernate.Mapping.Attributes 2.1.0 and Fluent NHibernate 1.0.0.545.

NHibernate classic style – XML-Files
For the class Cat I chose to use the classic way to map the class.

public class Cat
{
	private string id;
	private string name;
	private char sex;
	private float weight;

	public virtual string Id
	{
		get { return id; }
		set { id = value; }
	}

	public virtual string Name
	{
		get { return name; }
		set { name = value; }
	}

	public virtual char Sex
	{
		get { return sex; }
		set { sex = value; }
	}

	public virtual float Weight
	{
		get { return weight; }
		set { weight = value; }
	}
}

And the XML-File Cat.hbm.xml looks like:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernateTest.Domain" assembly="NHibernateTest">
	<class name="Cat" table="Cat">
		<id name="Id">
			<column name="CatId" sql-type="char(32)"/>
			<generator class="uuid.hex" />
		</id>
		<property name="Name">
			<column name="Name" length="16" not-null="true" />
		</property>
		<property name="Sex" />
		<property name="Weight" />
	</class>
</hibernate-mapping>

This approach has different problems: You couldn’t easily refactor your POCOs, you have to adapt the hbm.xml files too. Another problem is that you write your entity twice: in C# and in XML, so there is a lot of noise. This is the entry point for code generation, but it isn’t a real solution, it is just a workaround to handle the necessary XML file correctly and to reduce errors by manual writing.

NHibernate.Mapping.Attributes
For the class Dog I prefer the attributes to map the class. In JPA it is my preferred way for simple and small projects, so I was very interested how they ported this approach to .Net.

[Class(NameType = typeof(Dog))]
public class Dog
{
	private Guid id;
	private string strName;

	[Id(0,
	Column = "ID",
	Name = "ID",
	TypeType = typeof(Guid),
	UnsavedValue = "(00000000-0000-0000-0000-000000000000)"
	)]
	[Generator(1, Class = "guid.comb")]
	public virtual Guid ID
	{
		get { return id; }
		private set { id = value; }
	}

	[Property(0, Column = "Name",
	Name = "Name",
	TypeType = typeof(string),
	Length = 50,
	NotNull = false
	)]
	public virtual string Name
	{
		get { return strName; }
		set { strName = value; }
	}
}

Without the property NameType in the Class-attribute the sample doesn’t run. Another thing which disturbs me is the noise in the code by the attributes. It isn’t a clean POCO approach, also because the needed specific using statements.

Fluent NHibernate
Finally there is a third approach how to map a class. To demonstrate this possibility a use the Bird class:

public class Bird
{
	private Guid id;
	private string strName;

	public virtual Guid ID
	{
		get { return id; }
		private set { id = value; }
	}

	public virtual string Name
	{
		get { return strName; }
		set { strName = value; }
	}
}

For the mapping you have to use an additional class, which looks like that:

public class BirdMapping : ClassMap<Bird>
{
	public BirdMapping()
	{
		Id(x => x.ID);
		Map(x => x.Name);
	}
}

This approach is really interesting. You separate your mapping from your entity, but the mapping is written in the same language like the entity itself. So you can profit of the refactor features of your IDE or of an additional tool like Resharper.

Use all together in the same project
I tried to run all the three possibilities in one project and I used a factory method to create the NHibernate configuration instance. This method looks like that:

public static Configuration CreateConfiguration()
{
	Configuration config = new Configuration();
	config.Configure();

	// XML-Files
	config.AddAssembly(Assembly.GetExecutingAssembly());

	// Attributes
	HbmSerializer.Default.Validate = true; // Enable validation (optional)
	HbmSerializer.Default.Serialize(System.Environment.CurrentDirectory, Assembly.GetExecutingAssembly());
	config.AddDirectory(new DirectoryInfo(System.Environment.CurrentDirectory));

	// Fluent
	config = Fluently.Configure(config).Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>()).BuildConfiguration();

	return config;
}

In a real world application I wouldn’t recommend a such configuration. An architect should decide which mapping approach is adequate. But this code snippet demonstrate that it is possible to use all three mapping possibilities at the same time.

The secret fourth possibility
When I study NHibernate Fluent I saw on their wiki the possibility to use their Auto Mapping.

private static Configuration CreateAutoConfiguration()
{
	var config = Fluently.Configure()
				.Database(MsSqlConfiguration.MsSql2005.ConnectionString(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Test.mdf;Integrated Security=True;User Instance=True")
							.ShowSql())
				.Mappings(m => m.AutoMappings.Add(AutoMap
								.Assembly(Assembly.GetExecutingAssembly())
								.Where(t => t.Namespace == "NHibernateTest.Domain")))
				.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(false, true))
				.BuildConfiguration();

	return config;
}

The other three possibilities are a little bit different: there you define the mapping for each entity, which is more or less the opposite. You map by default all your entities by convention over configuration and only the exceptions have to be declared explicitly. Note that it is even possible to generate the DB schema with the ExposeConfiguration method.
For greenfield applications or prototypes it is a great way to map your entities, but for brownfield applications it is much harder to use. This is the case when you couldn’t discover a pattern in the database or in the entities, which you want to map. In a such scenario I would prefer one of the three other possibilities.

  • Share/Bookmark
Categories: .Net, Software engineering Tags: