Archive

Archive for the ‘.NET’ Category

Setting non-public property with type safety (no more strings)

November 30th, 2008 No comments

Sometimes I have a property where the get-part is public and the set-part is private or protected. Like this:

public class Forum

{

    public virtual int TopicCount { get; protected set; }

 

    // More code...

}

There can be various reasons for this design. For me it is often when I make database optimizations where I don’t want to be able to change a property directly in the code, but instead do it directly against the database.

Still, sometimes I want to set the value in unit tests. How do I do that?

Before C# 3.0 I had to rely on having a string with the property name and then use reflection. The main disadvantage with this approach is that if you rename the property you have to make sure that the string is also changed, which is time-consuming and error-prone.

So, with C# 3.0 you no longer need that string. You could use the new Expression-tree feature like this instead:

protected static void SetProperty<TObj, TValue>(TObj obj,

    Expression<Func<TObj, TValue>> property, TValue value)

{

    var propertyInfo = (PropertyInfo)((MemberExpression)property.Body).Member;           

    propertyInfo.SetValue(obj, value, null);

}

I have placed this method in my BaseTest class, since I only use it in my tests. Now you can write code like this to set the property:

var forum = new Forum();

SetProperty(forum, f => f.TopicCount, 2);

This is only a scratch on the surface of what you can accomplish with Expression-trees.

Categories: .NET, TDD Tags:

Testing your NHibernate data access code using SQLite

November 25th, 2008 No comments

Ever since I started working professionally at a software company (which is roughly 3 years ago) I’ve been doing unit testing. I really consider automatic testing one of the most (if not THE most) important trends of software development the last decade.

But, despite that, I’ve let code close to the data access be left untested. This has been due to the pain I thought it would be to create and maintain those tests. And also I’ve thought that those tests would be way to slow to have among my other unit tests (which we want to be fast, so that we run them often).

For the first two years of my career this was not a big problem. We rarely had bugs in our data access code as it mostly consisted of simple, straight forward code. So I hadn’t really given it much thought. Until lately that is.

Then we started to get performance issues as we got some really large organizations to use or software. To resolve the performance issues we made our data access smarter so it could make more efficient queries to the database. As smarter often means more code, or at least added complexity, I saw the need of automatic tests to guarantee the quality of the code.

So, I read some articles on using SQLite with NHibernate. After some pain setting it all up, I accomplished my goal of easy data access testing. So say that I want to test GetCustomerByName in the following class (in real life I wouldn’t test methods that are this simple, but it’s just to show the idea):

public class CustomerDao

{

    private readonly INHibernateManager _sessionManager;

 

    public CustomerDao(INHibernateManager sessionManager)

    {

        _sessionManager = sessionManager;

    }

 

    public Customer GetCustomerByName(string name)

    {

        var session = _sessionManager.CurrentSession;

 

        return session.CreateQuery("from Customer where Name = :name")

            .SetParameter("name", name)

            .UniqueResult<Customer>();

    }

}

Then I can write a test like this:

public class CustomerDaoTest : BaseTest

{

    [Test]

    public void CanGetCustomerByName()

    {

        Database.Init();

        var customerA = new Customer { Name = "A" };

        var customerB = new Customer { Name = "B" };             

        Database.Save(customerA, customerB);       

        var customerDao = new CustomerDao(Database);

 

        var result = customerDao.GetCustomerByName("B");

 

        Assert.That(result, Is.EqualTo(customerB));

    }

}

For this to work I have a class called TestDatabase with the following code:

public class TestDatabase : INHibernateManager

{

    private static ISessionFactory m_sessionFactory;       

    private static SchemaExport SchemaExport;

    private ISession m_session;

 

    public void Init()

    {

        if (m_sessionFactory == null)

        {

            Configuration config = CreateNHibernateConfig();

 

            m_sessionFactory = config.BuildSessionFactory();

 

            SchemaExport = new SchemaExport(config);

        }

        if (m_session != null)

        {

            m_session.Close();

        }

        m_session = m_sessionFactory.OpenSession();

        m_session.BeginTransaction();

 

        var connection = m_session.Connection;

        SchemaExport.Execute(false, true, false, false, connection, null);

    }

 

    private static Configuration CreateNHibernateConfig()

    {

        Configuration config = new Configuration();

        config.Properties.Clear();

 

        config.SetProperty("hibernate.connection.driver_class",

            "NHibernate.Driver.SQLite20Driver");

        config.SetProperty("hibernate.dialect", "NHibernate.Dialect.SQLiteDialect");

        config.SetProperty("hibernate.connection.connection_string",

            "Data Source=:memory:;Version=3;New=True;");

        config.SetProperty("hibernate.cache.use_second_level_cache", "false");

        config.SetProperty("hibernate.hbm2ddl.auto", "create");

 

        config.AddAssembly("MyAssembly"); // Change this to your assembly

 

        return config;

    }

 

    public ISession Session

    {

        get { return m_session; }

    }

 

    public void Save(params object[] entities)

    {

        foreach (var entity in entities)

        {

            Session.Save(entity);

        }

        Session.Flush();

    }

 

    ISession INHibernateManager.CurrentSession

    {

        get { return m_session; }

    }

}

And I’ve also added the following field to my BaseTest class:

[TestFixture]

public class BaseTest

{

    protected readonly TestDatabase Database = new TestDatabase();

 

    // More code here...

}

So, in summary, I’ve shown a pretty easy way of doing database testing. Even though the method under test was really simple in the example, the same technique could be used for much more complex scenarios.

Categories: .NET, NHibernate, TDD Tags:

Home from Öredev 2008

November 23rd, 2008 No comments

Friday night I came home from Öredev, a 3 day conference in Malmö. Overall, a great experience which has made me and the team I work with inspired.

The following are the most interesting experiences that I will take with me:

  • The Power of Value by Dan Bergh Johnsson. One of the best sessions of Öredev. An eye-opener for what value objects can do. A value object is an immutable object where you are not interested in tracking its identity. I will now begin to think more of this when developing.
  • Agile Architecture by James Coplien. James Coplien was a strange and arrogant person, for example claiming that he was 1 of 15 in the world who really understood object-orientation. But his ideas how architecture should be was really, really interesting. I think he is on to something with his gluing of Methodful Roles, Identifiers and Methodless Roles onto simple classes. Will definitely need to study this more as I only got a vague understanding of it.
  • Clean Code by Robert C. Martin. Uncle Bob (as he is also called) made two inspiring talks: the keynote and Clean Code III. I’ve had the pleasure of seeing him before at JAOO 2007, but despite that got more tips for writing good code. The rest of the team I work with, were also inspired, so we will try to enforce a clean code policy at work.
  • The Pomodoro Technique by Staffan Nöteberg. Staffan was a good speaker, using dolls and hats to make the speech fun. The Pomodoro technique is a process for improving one’s personal work. It’s main idea is to only be allowed to focus on one thing at a time. Will try this soon, both at work and at home.
  • The Lean thinking. Lean was mentioned by many speakers, Scott Bellware and James Coplien for example. It seems to be the new buzzword. I need to check up more on this, but I think I got the basic idea of it at least. Which is produce more value and eliminate waste.
  • Behaviour Driven Design. Got some ideas in this area from various sessions. MSpec as a framework looks interesting, especially the HTML-reports it can generate. AutoHotkey seems like a good utility for writing underscores more efficiently. Will start to use BDD-style both at work and at home.
  • T-person. Was mentioned by Scott Bellware. It basically is a person which is good at other things than his main speciality. Like a developer that also is skilled at design and testing. Then he can help in both of those areas if needed and also his understanding will make hand-offs smoother.
  • Design Debt. Got a good scetch model to illustrate how design debt works for people that don’t understand it (like managers).

I learned many more things during the conference, but I have to stop now. Probably there will be more posts later on as I try out some of the new ideas I’ve got.

Categories: .NET Tags:

AutoStub parameters using Rhino Mocks

November 16th, 2008 No comments

For the last years I’ve been using dependency injection for my service classes. More recently (by the introduction of ASP.NET MVC) that have also been the case for my controller classes. I take in their dependencies via the constructor and then let a Dependency Injection/Inversion of Control (DI/IoC) framework automatically resolve and create the classes. I’ve been using Castle Windsor for this, which has worked really well.

However, when it comes to testing service/controller classes, I’ve previously created (often stubbed) the parameters needed when testing, and then given them manually to the constructor. Like this:

var customerDao = Stub<OrderDao>();

var orderDao = Stub<OrderDao>();

var controller = new CustomerController(customerDao, orderDao);

This has proven to be quite fragile as the dependencies to the service/controller class has changed. Often, the case has been that more dependencies have been added as parameters to the constructor. I know, I know, that might be a code smell that the service/controller should be split into smaller classes… But anyway, code smell or not, the fragility of the tests is a problem.

A while back I read about an AutoMocking container, but thought it was a bit cumbersome to have to use both a Mocking framework and a DI/IoC container in my tests. So, I thought that this should be possibly to accomplish with only a mocking framework and a bit of reflection magic. And it actually turned out to be really easy to do.

As a mocking framework I use Rhino Mocks (btw, I love the new AAA syntax in 3.5!). All my test inherit from a class called BaseTest, which is where I decided to put the autostubbing. The code comes here:

[TestFixture]

public class BaseTest

{

    protected static T Stub<T>(params object[] parameters) where T : class

    {

        return MockRepository.GenerateStub<T>(parameters);

    }

 

    protected static T Mock<T>(params object[] parameters) where T : class

    {

        return MockRepository.GenerateMock<T>(parameters);

    }

 

    protected static T CreateAndAutoStubParameters<T>(params object[] parameters)

    {

        return (T)CreateAndAutoStubParameters(typeof(T), parameters);

    }

 

    protected static object CreateAndAutoStubParameters(Type type,

        params object[] parameters)

    {

        var constructor = type.GetConstructors(

            BindingFlags.Public | BindingFlags.Instance)[0];

        var parameterInfos = constructor.GetParameters();

        var constructorParams = GetConstructorParameters(

            parameterInfos, parameters);

 

        return constructor.Invoke(constructorParams.ToArray());

    }

 

    private static List<object> GetConstructorParameters(ParameterInfo[] parameterInfos,

        params object[] parameters)

    {

        var constructorParams = new List<object>();

        foreach (var info in parameterInfos)

        {

            constructorParams.Add(GetParameter(info, parameters));

        }

        return constructorParams;

    }

 

    private static object GetParameter(ParameterInfo info,

        object[] candidateParameters)

    {

        foreach (var candidate in candidateParameters)

        {

            if (info.ParameterType.IsAssignableFrom(candidate.GetType()))

            {

                return candidate;

            }

        }

        return AutoStub(info.ParameterType);

    }

 

    protected static T AutoStub<T>() where T : class

    {

        return (T)AutoStub(typeof(T));

    }

 

    protected static object AutoStub(Type type)

    {

        if (type.IsInterface)

        {

            return MockRepository.GenerateStub(type);

        }

 

        var constructor = type.GetConstructors(

            BindingFlags.Public | BindingFlags.Instance)[0];

        var parameterInfos = constructor.GetParameters();

        var constructorParams = GetConstructorParameters(parameterInfos);

 

        return MockRepository.GenerateStub(type, constructorParams.ToArray());

    }

}

So, now let us assume you want to test a CustomerController with dependencies like this:

public class CustomerController

{

    public CustomerController(CustomerDao customerDao, OrderDao orderDao)

    {

        // Code here..

    }

 

    // Code here..

}

Then you only have to write this:

var controller = CreateAndAutoStubParameters<CustomerController>();

to create the controller with stubs automatically created as constructor parameters.
Often, you might want to have some control over one of the parameters, and then you could write like this:

var customerDao = AutoStub<CustomerDao>();

customerDao.Stub(c => c.GetById(1)).Return(new Customer());

var controller = CreateAndAutoStubParameters<CustomerController>(customerDao);

This way of testing service and controller classes has removed some of the pain of starting to test classes with dependencies that need to be mocked or stubbed.

Categories: .NET, Rhino Mocks, TDD Tags:

Validating HTTP method in ASP.NET MVC

July 10th, 2008 No comments

On the web it’s considered a good practice that the GET method never changes the state on the server. When state should be changed the POST method should be used. It is good to follow this practice, otherwise there might be problems when search engines tries to visit links (which are GET by default).
By default in ASP.NET MVC any public method on the controller can be accessed both by GET and POST. So I _could_ access my DeleteUser() method by an ordinary link (which is GET).

So, how do I restrict a method in ASP.NET MVC to be only GET or only POST? I could use ActionFilterAttribute and tag each method with it. But tagging every method is a bit noisy in my opinion. The thing I want is GET to be the default way to access methods, and then I want to mark POST methods only with attributes.

In my MVC projects I always have a BaseController, that all my controllers inherit from. With that in place it is actually quite easy to accomplish the above. I just need to override OnActionExecuting like this:

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var attributes = filterContext.ActionMethod.GetCustomAttributes(
            typeof(POSTAttribute), false);
        var method = filterContext.HttpContext.Request.HttpMethod;
        if (attributes.Length > 0 && method != "POST")
        {
            ThrowIllegalMethodException("POST", filterContext);
        }
        else if (attributes.Length == 0 && method != "GET")
        {
            ThrowIllegalMethodException("GET", filterContext);
        }
    }

    private static void ThrowIllegalMethodException(string expectedHttpMethod,
        ActionExecutingContext filterContext)
    {
        var controllerName = filterContext.Controller.GetType().Name;
        var controllerMethod = filterContext.ActionMethod.Name;
        var httpMethod = filterContext.HttpContext.Request.HttpMethod;

        var message = string.Format("Only {0} method allowed for {1}.{2}, but {3} was used.",
            expectedHttpMethod, controllerName, controllerMethod, httpMethod);
        throw new SecurityException(message);
    }
}

And also I need a POSTAttribute which is simplest possible:

public class POSTAttribute : Attribute
{
}

So, now I can write [POST] above methods like this:

public class MyController : BaseController
{
    [POST]
    public ActionResult SaveMyEntity()
    {
        // Code..
    }
}

Pretty cool that you can change the behaviour of the MVC framework this easy.

Categories: .NET, ASP.NET, ASP.NET MVC Tags: