Partitioning NHibernate IRepository to achieve better SRP level (hopefully!)

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

As you might know for some time now I’ve been working on my own NHibernate implementation. Largely it is influenced by Ayende’s great Rhino.Commons for NHibernate, but what I like to think is that it took a little bit different direction, and that the details of implementation are what it makes really different (not better or worse… just different).

With this in mind I am working on my own IRepository implementation and have found that it actually has at least 3 reponsibilities it must fullfill:

  1. It must be able to Save/Update/Delete/Query Entities
  2. It must be able to Query for DTO’s (via projections)
  3. It must be able to call Stored procedures

Now, with Ayende’s REALLY great implementation all this is a part of the main IRepository interface, what I’ve decided is that in my implementation they will be split:

  • IEntityRepository
  • IStoredProcedureRepository
  • IProjectionRepository

This allows me to split the responsibilities more accurately over them. Some of the differences:

  • IEntityRepository<EntityT> is full featured - it can both query and save/update/delete mapped entities
  • IStoredProcedureRepository contains only methods to call stored procedures
  • IProjectionRepository also only contains querying possibilities, it can query very similary to Entity repository, difference being that here you define the projections as well and thus tranform the result to a DTO or something else. Also, instead of defining the resulting type on the repository level (IRepository<T>), here you define it on a query level (.Find<T>….)

What do you think of a such idea?

I have to mention that the first two repositories are already made (Entity and Stored procedure), and are fully tested (spec’d out).

Ill describe how the current ones look in a series of upcoming posts, but they do contain some neat things.

Cheers!


Filed under: Akua.Framework, BDD, C#, NHibernate
Written on: 21 Apr 2008 · No Comments »

Naming in my BDD-style Specification base class

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

One thing I really like in my BDD specification base class (found here) is how I’ve renamed the Rhino Mocks - Record - Playback model to be more expressive.

However, there is one part I am really not happy with… the naming of the Playback using statement.

Currently I’ve put it of as “What_SUT_Should_Result_To” but that doesn’t really express what the code does inside… my suspicions were confirmed this morning also by JP who mentioned that it looks good, but that he is not in love with that method name.

So, what could I call it to make it express intent better? Here are some examples:

- How_SUT_should_be_used
- When_SUT_is_used
- When_SUT_functionality_is_used
- When_SUT_is_used_like
- When_SUT_functionality_is_used_like
- When_SUT_is_called
- When_SUT_functionality_is_called

The sound of “When_SUT_functionality_is_used_like” sounds good in combination of the previous using statement:

using (How_SUT_should_Behave) {
           …
}

using (When_SUT_functionality_is_used_like) {
            …
}

What do you think? Do you have any ideas?

Cheers!


Filed under: BDD, C#
Written on: 16 Jan 2008 · No Comments »

BDD and ASP.NET MVC… a match made in heaven

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

Whilst preparing for my user group session on MVC I’ve upgraded my BDD base class (actually subclassed it) with specifics related to specifying the behavior of MVC routes and controllers.

I’ve made for starters 2 new classes:

public class MvcMockedHttpContext
{
    private readonly MockRepository _mocks;
    private IHttpContext _context;          

    public MvcMockedHttpContext(MockRepository mocks)
    {
        _mocks = mocks;
    }          

    private void _CreateMocked()
    {
        _context = _mocks.DynamicMock<IHttpContext>();          

        SetupResult.For(_context.Request)
		.Return(_mocks.DynamicMock<IHttpRequest>());
        SetupResult.For(_context.Response)
		.Return(_mocks.DynamicMock<IHttpResponse>());
        SetupResult.For(_context.Session)
		.Return(_mocks.DynamicMock<IHttpSessionState>());
        SetupResult.For(_context.Server)
		.Return(_mocks.DynamicMock<IHttpServerUtility>());          

        _mocks.Replay(_context);
    }          

    public IHttpContext ReturnMocked
    {
        get
        {
            if (_context == null) _CreateMocked();          

            return _context;
        }
    }
    public MvcMockedHttpContext FakeoutUrlRequest(string url)
    {
        if (_context == null) _CreateMocked();          

        SetupResult.For(_context.Request.AppRelativeCurrentExecutionFilePath)
                        .Return(url);
        SetupResult.For(_context.Request.PathInfo)
                        .Return(string.Empty);          

        return this;
    }
    public MvcMockedHttpContext FakeoutApplicationPath(string path)
    {
        if (_context == null) _CreateMocked();          

        SetupResult.For(_context.Request.ApplicationPath).Return(path);          

        return this;
    }          

}

Which I use to mock out the HttpRequest quickly and it serves me as a small mock out DSL for often used tasks with mocking the HttpRequest

Second part is the upgraded specification class:

public class MvcContextSpecification : ContextSpecification
{
    public MvcMockedHttpContext HttpContext
        {
            get
            {
                MvcMockedHttpContext context = new MvcMockedHttpContext(Mocks);
                return context;
            }
        }          

    public TController
                  CreateTestableControllerOf<TController>
                                                (string routeDataController,
                                                 string routeDataAction,
                                                 params object[]
                                                        paramsForControllerConstructor)
        where TController : Controller
    {
        TController controller =
                            CreateMockOf<TController>(paramsForControllerConstructor);          

        RouteData routeData = new RouteData();
        routeData.Values.Add(“Controller”, routeDataController);
        routeData.Values.Add(“Action”, routeDataAction);          

        IHttpContext context = HttpContext
                                    .FakeoutApplicationPath(“/”)
                                    .ReturnMocked;          

        controller.ControllerContext
                     = new ControllerContext(context, routeData, controller);          

        return controller;
    }          

    public bool HasActionActionAttribute<TController>
                                       (Expression<Action<TController>> action)
    {
        StringBuilder sb = new StringBuilder();
        MethodCallExpression call = action.Body as MethodCallExpression;
        if (call == null)
            throw new InvalidOperationException(“Expression must be a method call”);
        if (call.Object != action.Parameters[0])
            throw new InvalidOperationException(“Method call must target lambda argument”);          

        Attribute attribute
                       = Attribute.GetCustomAttribute(call.Method,
                                                      typeof(ControllerActionAttribute));          

        return (attribute != null);
    }
}

These 2 classes are my base for BDD with MVC (although admittedly this is for the combination of TDD and BDD, because although I am mostly testing the behavior at some parts I am testing the configuration as well)

Now comes the sweet part… how does this look implemented?

Let me show you an example of specifying the routes:

[Specification]
public void And_the_Selected_route_data_should_resolve_default
                                   _route_when_default_url_is_received()
{
    using (How_SUT_should_Behave)
    {
        _httpContext = HttpContext
                            .FakeoutUrlRequest(“~/default.aspx”)
                            .ReturnMocked;
    }          

    using (What_SUT_should_Result_to)
    {
        RouteData routeData = _routes.GetRouteData(_httpContext);          

        Assert.IsNotNull(routeData);
        Assert.AreEqual(“home”, routeData.Values["controller"]);
        Assert.AreEqual(“index”, routeData.Values["action"]);
    }
}

Sweet, isn’t it? Let me show the controllers:

[Context]
public class When_OrdersController_List_action_is_called
                                         : MvcContextSpecification
{
    [Specification]
    public void Then_List_view_should_be_displayed_and_OrdersService
                                                 _should_get_the_data_for_view()
    {
        IOrdersService mockedOrdersService = CreateMockOf<IOrdersService>();          

        OrdersController controller
                  = CreateTestableControllerOf<OrdersController>(“orders”,
                                                                 “list”,
                                                                 mockedOrdersService);          

        IList<Order> dummyOrders = _GetDummyOrders();          

        using (How_SUT_should_Behave)
        {
            Expect.Call(mockedOrdersService.ListAll()).Return(dummyOrders);          

            controller.RenderView(“List”, dummyOrders);
        }          

        using (What_SUT_should_Result_to)
        {
            controller.List();
        }
    }          

    [Specification]
    public void And_List_action_should_have_an_action_attribute()
    {
        Assert.IsTrue(HasActionActionAttribute<OrdersController>(x => x.List()));
    }          

    private List<Order> _GetDummyOrders()
        {
            return new List<Order>{
                            new Order(),
                            new Order(),
                            new Order()
                        };
        }
}

I’ve mentioned this to Joe Ocampo… I am struggling with myself to try to write the vanilla unit tests now for my session so that the attendees can more easily grasp the concepts in testing the MVC controllers and routes, and I must admit that… I DON’T WANT TOOO!!! I like my specifications, they feel so “right”.

What do you think? As with the previous BDD article… I would love your comments is this any good or bad?

Cheers!


Filed under: ASP.NET MVC, BDD, C#
Written on: 13 Jan 2008 · No Comments »

My variation of the BDD style specification base class

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

So lately I’ve been playing with BDD at home trying to *grok* the idea completely… as many people have said it in the past, one just needs to look pasted the *test* naming and understand your not doing BDD by naming your tests in natural sentence way… that’s just the tip of an iceberg.

However, to fully grasp the concept (I am still not 100% sure I have, but I am somewhere around hitting the target) one thing you definitely need is to bring the expressiveness in your tests (there I go again… Specifications) a few notches up to see the bigger picture.

So what I’ve done is… I took JP’s spec base class:

http://www.jpboodhoo.com/blog/BDDSpecificationBaseClass.aspx

…gave it my own touch and out came my version which is for me personally allot more expressive in it’s intent to describe the behavior of a functionality.

One great thing is that JP implemented and I followed Rhino Mocks and AutoMockingContainer which makes testing or specifying things allot better, faster and more natural (read JP’s article to get the idea of the full power of his Spec base).

Here it is my way:

public abstract class ContextSpecification
{
    private MockRepository _mocks;
    private AutoMockingContainer _container; 

    protected MockRepository Mocks
    {
        get { return _mocks; }
    }
    protected AutoMockingContainer Container
    {
        get { return _container; }
    } 

    [SetUp]
    public void BaseSetup()
    {
        _mocks = new MockRepository();
        _container = new AutoMockingContainer(_mocks);
        _container.Initialize(); 

        Before_Each_Specification();
    }
    [TearDown]
    public void TearDown()
    {
        After_Each_Specification();
    } 

    protected virtual void Before_Each_Specification()
    {
    }
    protected virtual void After_Each_Specification()
    {
    } 

    protected IDisposable How_SUT_should_Behave
    {
        get { return Mocks.Record(); }
    }
    protected IDisposable What_SUT_should_Result_to
    {
        get { return Mocks.Playback(); }
    }
    protected void Verify_Behavior_of(object mock)
    {
        _mocks.Verify(mock);
    }
    protected void Verify_Behavior_of_All_Objects()
    {
        _mocks.VerifyAll();
    }
    protected void Replay_Specified_Behavior_of(object specifiedObject)
    {
        Mocks.Replay(specifiedObject);
    }
    protected void Replay_Specified_Behavior_of_All_Objects()
    {
            Mocks.ReplayAll();
    } 

    protected T Mock<T>() where T : class
    {
        return _container.Get<T>();
    }
    protected T Create<T>()
    {
        return _container.Create<T>();
    } 

    protected void ProvideAnImplementationOf<Interface, Implementation>()
    {
        _container.AddComponent(typeof(Implementation).FullName,
                                        typeof(Interface),
                                        typeof(Implementation));
    }
    protected void ProvideAnImplementationOf<Interface>(object instance)
    {
        _container.Kernel.AddComponentInstance(instance.GetType().FullName,
                                            typeof(Interface), instance);
    } 

    protected IEnumerable<T> CreateEnumerableMockOf<T>()
    {
        return CreateMockOf<IEnumerable<T>>();
    }
    protected Interface CreateMockOf<Interface>(params object[] paramsForConstructor)
    {
        return Mocks.DynamicMock<Interface>(paramsForConstructor);
    }
    protected Interface CreateStrictMockOf<Interface>(params object[] paramsForConstructor)
    {
        return Mocks.CreateMock<Interface>(paramsForConstructor);
    }
    protected Interface CreatePartialOf<Interface>(params object[] paramsForConstructor)
                            where Interface : class
    {
        return _mocks.PartialMock<Interface>(paramsForConstructor);
    }
    protected Interface CreateStubOf<Interface>(params object[] paramsForConstructor)
    {
        return _mocks.Stub<Interface>(paramsForConstructor);
    } 

}

And how do I use it, well it’s quite simple. Here is an example of the *loong* way-round specifying the behavior of an ASP.NET MVC route.

First my Specification template imports these:

using Context = MbUnit.Framework.TestFixtureAttribute;
using Specification = MbUnit.Framework.TestAttribute;

Then I use them like this:

[Context]
public class When_RouteContainer_is_configured : ContextSpecification
{
    private RouteCollection _routes;
    private IHttpContext _httpContext; 

    protected override void Before_Each_Specification()
    {
        _routes = new RouteCollection();
        RouteContainer.Initialize(_routes);
    } 

    [Specification]
    public void Then_RoutesCollection_should_be_initialized()
    {
        Assert.IsNotNull(_routes);
    } 

    [Specification]
    public void And_RoutesCollection_should_contain_2_routes()
    {
        Assert.AreEqual(_routes.Count, 2);
    } 

    [Specification]
    public void And_the_Route_data_should_resolve_default_route_when_default_url_is_received()
    {
        using (How_SUT_should_Behave)
        {
            _httpContext = CreateMockOf<IHttpContext>(); 

            IHttpRequest request = CreateMockOf<IHttpRequest>();
            SetupResult.For(_httpContext.Request).Return(request); 

            Replay_Specified_Behavior_of(_httpContext); 

            SetupResult.For(_httpContext.Request.AppRelativeCurrentExecutionFilePath)
                            .Return(“~/default.aspx”);
            SetupResult.For(_httpContext.Request.PathInfo)
                            .Return(string.Empty);
        } 

        using (What_SUT_should_Result_to)
        {
            RouteData routeData = _routes.GetRouteData(_httpContext); 

            Assert.IsNotNull(routeData);
            Assert.AreEqual(“home”, routeData.Values["controller"]);
            Assert.AreEqual(“index”, routeData.Values["action"]);
        }
    }
}

Notice a few things:

  • Usage of different attribute naming to express intent
  • Usage of When…Then…And naming to express continuity
  • Expressiveness of the specification itself - notice the last one - read it from bottom up - The result of the work done with SUT, or When SUT is used in this particular way (”What_SUT_should_Result_to”) it’s behavior should be (”How_SUT_should_Behave”) …

What do you think? Comments would be appreciated.

If anyone is interested in the real code, it will be published in the near future as part of my (future) code repository.

Cheers!


Filed under: ASP.NET MVC, BDD, C#
Written on: 13 Jan 2008 · 2 Comments »

Provable value of BDD (or YABDDIP – Yet Another BDD Intro Post)

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

As I am a semi-novice TDD developer (although the following remarks are more intended for your classical Unit testing developer, simply because I am talking about testing, not designing which is the point of TDD. And also I am considering myself as a semi-novice because I’ve actually been convinced with the idea for so long, even done some projects, but I am still having problems enforcing it in my company) I’ve always found myself troubled by a rather simple question:


How can I know that a given functionality (or a piece of code) is tested? Or how do I know that a developer working with me in a team has tested it and/or written it completely?

I mean… I can write 5 tests for a given functionality, my colleague can write only 1 and a TDD expert can write 20.

We will all be convinced that we have done a good job testing that piece of code – I will test it partially, TDD expert will test it probably 90% and my colleague will only smoke test it.

Without looking in details at the tests, how would I know who of us made a good job of it?

And even better… did any of us?


To be able to answer that… we would need to set up a baseline – or even better, what are we measuring against?

If you think… the code did not brake… well, in all 1-20 tests of all three of us it didn’t?!?
If you think… it does what it needs to… how do you know that it does? Even if TDD expert did write 20 tests, maybe he missed a couple of important use cases of a given code fragment.

Note that this concern is even magnified with TDD – where you try to write as little code as possible to satisfy a given functionality – this is one of the core ideas of TDD – and one of the areas where I see it really excel – not writing un-needed code and tests.

I can write a code to satisfy 90% of the logic – and that part will be 70% tested – how do I know these numbers? Well I don’t. I can only guess – as much as anyone – what is important that our tests cover our imaginary design – and it is imaginary – because at a given fragment of time – we only think that our functionality is done, or that our design fits correctly into the bigger picture – we can think it is, we can even have some indications and be reasonably sure it is – but is it really?

Or a better question – when a developer comes to us and says, I’ve developed it – it’s tested and working – I’ve written 50 tests to cover the code – is that enough? Is the functionality done?


What I am missing in both cases (and have been when thinking about these ideas) is the acceptance criteria – plain and simple – I want to be 100% sure that if I wrote 5 tests – that those tests mattered, and that they test what they need to. I don’t want to rely on my (or my colleagues) experience and proficiency at testing – nor design for that matter.

(I sound harsh… sorry! I am not putting names or blames on anyone – nor do I miss confidence in my dev. team - but we are all professionals – and if I want to be professional about what I do – I must be exact and correct – and more important – I cannot go check every bit of my colleague’s code and tests against the client’s requirements)


Now… before going further… please don’t think that I see the following (BDD) as a silver bullet to answer the asked question – simply a technique to improve my teams scoring on the subject.

So, what would I want – I would want something measureable - for example, with a given task, a check list of things that a given piece of code must do or rules it must conform to.

That is great – but the problem is that it’s still not executable, and thus must be confirmed manually – so really yuck!


Here is where I see that Behavior Driven Development comes into play.

If we start with the behavior – and work towards the functionalities – and that behavior is pre-defined in the form of scenarios of a given story – we can have pretty solid acceptance criteria for our team’s developers to follow.


Before moving on, take a look at these great links:

http://dannorth.net/whats-in-a-story

http://persistall.com/archive/2007/11/02/bdd-with-just-nunit—a-first-attempt.aspx


If I see it through the eyes of BDD – my talk to my fellow developer might be:

When showing the list of customers, note that that list must be:

- Should return an appropriate message if no customers are found in the database
- If shown should be paged with 10 records at a time
- Should show the customers ordered by their first name
- Should have options to edit or delete a customer

So I am talking about the context:

“…When showing the list of customers…”

And I am giving the acceptance criteria to my fellow developer:

- Should return an appropriate message if no customers are found in the database
- If shown should be paged with 10 records at a time
- Should show the customers ordered by their first name
- Should have options to edit or delete a customer

That developer can now easily make a Fixture:

When_showing_the_list_of_customers

With the tests:

Should_return_an_appropriate_message_if_no_customers_are_found_in_the_database
If_shown_should_be_paged_with_10_records_at_a_time
Should_show_the_customers_ordered_by_their_first_name
Should_have_options_to_edit_or_delete_a_customer


This is a lot more un-ambiguous from the start! I see advantages from all 4 points of view:

Team Leader – I am happy to finally be able to communicate to both developer and the client the acceptance criteria of a given functionality and to hold and be held accountable by it (remember that being a professional part?)

Developer – I am happy to know 100% what I need to do my job correctly – there should be no misunderstandings or “I think…”, “But, You said…” troubles

Client – I am happy with the level of professionalism at which the team communicating with me. I am can easily add to the list things that I see missing (it is so simple). I get more predictability and accountability for my money

Manager – I get more predictability (and managers really dig this oneJ) for my (clients?) money


Sounds good doesn’t it?

To me too :)


And all of this while practicing the great ideas of TDD and Unit Testing!

Disclaimer again: It is not a silver bullet! You will hit a wall with C# limitations, with questions you will ask yourself (see Brian Donahue’s post above for some self-questions) – but it is a huge step up and in the right direction!


What do you think?


Filed under: BDD
Written on: 04 Nov 2007 · 2 Comments »

Ones of the best BDD intros I’ve read so far…

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

… which doesn’t mean that I’ve read quite a bit of them, just that it finally explains the *context* (since I am new to it) of BDD to it.

I especially like this part (which hits the spot for me):

“…Now, if you already do TDD (and Model-View-Presenter as in this example) you might say “big deal, I already do it this way, without the ridonkulously long test names!”. And you’d probably be right. But in my experience, instead of this context focused test, I’d end up with one big OrderHistoryPresenterTest in which I’d try to test everything that would ever be asked of the OrderHistoryPresenter and I’d probably get stuck a bunch of times wondering if X or Y function belongs on this presenter, or somewhere else. Then I’d move on to the OrderService and hit the same problems. With BDD, I can focus on one behavior, and drive it all the way out down through my entire application stack. …”


Go read it, it’s definetly a great read:

http://persistall.com/archive/2007/11/02/bdd-with-just-nunit—a-first-attempt.aspx


One more thing I’ve found while reading the AltNet mailing list, a stab at being more BDD with C# 3.0 by Scott Bellware:

http://codebetter.com/blogs/scott.bellware/archive/2006/12/18/156436.aspx


All I can say that I am bought with the idea… now I need to find some more concrete samples (like the example above) to get me up to speed…


Cheers!


Filed under: BDD
Written on: 04 Nov 2007 · No Comments »