Func<code>

A journey

Quick’n dirty with MbUnit: How to get a failing test..to succeed!

clock January 20, 2009 17:32 by author daniel

To facilitate with my coding I have decided to progressively build a small library to help on the testing side of things. On the project I am currently involved with MbUnit is our testing framework of choice.

I was faced today with the problem of adding a new Assertion method but as you probably already know it, Extension Methods don’t work against static classes, they only work against instance classes, maybe a low priority for either the CLR or C# team.

So instead of extending the Assert class one might just create yet another static class that looks and behaves as the ones built in MbUnit. This is easily done by using the generic Assert.Fail(string description) method to notify the framework of a failure,


For instance here is an example of such assertion that checks the length of a IEnumerable:



  
public static class EnumerableAsserts {
 
       public static void VerifyContainsFiveItems<T>(IEnumerable<T> list)
       {
            if (list.Count() != 5)
                Assert.Fail("The count of predicates should match the one from the list.");
       }

 }
 

All is well and good except that I wanted to test the assertions themselves, EnumerableAsserts.VerifyContainsFiveItems<T>(IEnumerable<T> list) in our example, by using MbUnit itself as my test framework and some of those tests required tests to actually fail.

But if I do

[Test]
public void FailIfHasOneItem() {
       VerifyContainsFiveItems(new List<string>() {“Foo”});
} 

 

The test above will always fail because VerifyContainsFiveItems will raise a failed assertion and there is nothing we can do about it. I haven’t had the time to find a way to swallow all failed assertions within a block.

The quick’n dirty solution I found round this limitation was to create a new class attribute deriving from TestAttribute. Indeed after some analysis I noticed that this class does have quite a fair bit.
The new class, FailingTestAttribute allows us to override MbUnit default behaviour in deciding if a test succeeded or not

With this following test I can now do the following and it will tell me the test succeeded.

[FailingTest]
public void FailIfHasOneItem() {
      VerifyContainsFiveItems(new List<string>() {“Foo”});
} 

 

whereas the following test will fail :

[FailingTest]
public void WillFailBecauseItSucceededDoh() {
      VerifyContainsFiveItems(new List<string>() {“1”,“2”,“3”,“4”,“5”});
} 

 

Here below is the code of the new attribute :

public class FailingTestAttribute : TestAttribute
    {
        protected override object Execute(PatternTestInstanceState state)
        {

            if ((state.TestMethod != null) && (state.TestArguments != null))
            {

                try
                {
                    var @out = ExceptionUtils.InvokeMethodWithoutTargetInvocationException(state.TestMethod, state.FixtureInstance, state.TestArguments);
                }

                catch (AssertionFailureException e)
                {
                    // Return null to imply the Failing Test has failed and therefore should succeed
                    return null;
                }

                throw new AssertionFailureException(new FakeFailure(state), false);
            }

            return null;

        } 

        public class FakeFailure : AssertionFailure
        {

            public FakeFailure(PatternTestInstanceState state)

                : base("A Failing Test has not failed.", state.TestMethod.Name, new StackTraceData("null"), new List<LabeledValue>(), new List<ExceptionData>(), new List<AssertionFailure>())

            {}

        }      

    }

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Beware of the F-word!

clock December 17, 2008 11:11 by author daniel

I’m talking of F as in Framework.
A Framework is a highly cohesive set of classes that enable developers to build systems, and one might argue a Framework should be shipped in a separate set of packages.
The danger of a Framework is that although it sounds compelling to use a project to build such a thing, this can easily lead to extra code that is unused for the “other cases” that may never materialize.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ORM, Persistence Ignorance with Legacy Databases

clock December 10, 2008 05:04 by author daniel

I am currently involved in a project aiming to re-write an existing Intranet frontend for a FTSE250  insurance firm in the UK.
The existing Intranet was built with .Net 1.1 by ex VB6 developers with a poorly structured code and no sign of a layered architecture with SQL code littered throughout the application and no classes to model the domain.

If that wasn’t bad enough, the database this system is providing a frontend for has clearly not been built following the principles of OLTP databases. More on this later.

The reason why this is an issue is that we’ve all used Object Relational Mapping (ORM) tools in the past and it’s been decided to use NHibernate to provide the concrete implementation of our Data Access Layer which is exposed using the Repository pattern.

Things that are making it difficult for us application developers with a fairly good experience with NHibernate:

Data structure

And ORM requires a good database structure, with a fair amount of normalization. The thing that hit me several times is that a lot of developers are ready to lose some of the basic OO principles when designing a database at the same time as creating their domain model. NHibernate does support interesting concepts such as Many-to-Any relationships that can enable polymorphic associations between entities (class Foo : IFoo {IBar Bar {get;set;}}).

With poor data structure we may end up with unwanted data duplication and sometimes with a substantial gap between how the data is structured and the understanding someone would have just by looking at the frontend. For instance Many-to-Many “business” relationships done in only 2 tables..

Auditing

Version Auditing done in the same table as the table that is audited, instead of using another table which is better in my opinion, we end up with an extra Version column that has to in effect be part of the composite key now.

I am not sure what’s the best solution but I would favor a FooAudit table containing the exact same columns from Foo.

Multi-tenancy with Composite Keys

Multi-tenancy with Composite Keys. Having read several times the advice not to use Composite Keys with NHibernate and to instead use Surrogate Keys we’ve had a really hard time mapping the database to an object model, one of our team members even had to patch NHibernate so that we can support a fairly simple Man- to-One relationship between tables containing shared elements of their Composite Keys such as:

Table1 has a Composite Key formed of keys Table1KeyA, Table1KeyB and Table1KeyC
Table2 has a Composite Key formed of keys Table2KeyA and Table1KeyB

NHibernate doesn’t support this model natively because it expects to only hold distinct set of columns for foreign keys from its primary key columns (in Table1 so that it holds a reference to Table2).As we haven’t got experience with Multi-Tenanting we’ve probably done some early mistakes that may cost us dear in the future, for instance it may be best not to use the keys involved in the Multi-Tenanting part of the Primary Keys and use some interceptors to set those up when making queries or by using filters.

 

We’re obviously not the only ones having to try to map a Domain Model on top of a Legacy Database with an ORM. Like so many before us, we had to create Database Views to create associations between tables or even hacks directly from within entities themselves. All this make it very difficult to reach Persistence Ignorance and this is a lesson learned that there is a fundamental difference between a Database built by DBAs and Application Developers who will favor Surrogate Keys.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Domain Model + Repository isn't necessarily DDD

clock December 5, 2008 02:18 by author daniel

Having worked on several .Net Web projects in the past few years I have encountered several times roughly the same architectural pattern called the Onion architecture which is a layered architecture.

For instance we have the UI layer (MVP, MVC for instance) which depends upon various Services which themselves depend upon the Domain Model.
Access to the persistence store, say a relational database, is done through a set of specialized data access classes that used to be called Data Access Objects (DAOs) but now are called Repositories. Those persistence related classes provide basic CRUD like commands in addition to querying and sometimes with parameterized commands where parameters use Specification or the Prototype patterns or simply simple CLR objects.
Sometimes those layers implementations sit within their own packages (Assemblies) to enforce the direction of dependencies and some might rightly argue this is neither useful or worse it's an impediment but that’s a difference subject.

Those no now called Repositories can usually be referenced by either UI Controllers or Application Services depending on styles and needs.

In DDD, a Repository, usually one per Aggregate Root, is a first class Domain citizen with the sole purpose of abstracting the persistence store (database) by simulating an in-memory collection of Domain objects

This does sound very much like a DAO, and in practice a Repository might delegate functionality to a DAO via Composition.

The core difference in between a Repository and a DAO is that in my view a Repository can be called by Domain entities themselves, this is so to avoid unnecessary or illogical transversal associations between Domain entities for the sole purpose of getting round the fact that it's not possible to query a Repository from wihin the Domain.
The other, very important, added benefit is that the Domain entities are empowered and therefore helps in making sure that business logic resides in the Domain and not in higher levels such as Application services or UI Controllers.
If one doesn't want to directly use a Repository from within the Domain, it could be possible to instead use Domain Services that can themselves be composed of Repository objects.
Not that there isn't much consensus in the DDD community as one can see here.

References:

http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215

http://www.manning-sandbox.com/message.jspa?messageID=51425

http://codebetter.com/blogs/ian_cooper/archive/2008/12/03/the-fat-controller.aspx

http://www.infoq.com/minibooks/domain-driven-design-quickly

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Spikes != Research

clock October 22, 2008 17:02 by author daniel

I am involved in a new project using some of the latest technologies in the .Net sphere, such as .Net framework 3.5, Sync Framework and most specifically Windows Presentation Foundations, aka WPF.

Due to an obvious lack of WPF expertise in the industry, my employer took the reasonable decision to hire  developers knowing that they would have to “learn on the job” on how to develop applications with WPF.

I got involved in this project after quite a few iterations and having developed with WPF in the past myself I know that this platform is substantially different from first Web development, for a large number of reasons but Windows Forms as well. I was told that several spikes were made as proof-of-concepts to help mainly Web developers.

Having actually seen some of the implementation it is pretty clear that the developers never had the chance/time to read a good WPF book. And I will be honest about it all myself, I still learn about smart client development everyday.

So what I’ve learned is that a Spike just can’t replace Research (google, blogs, books or friends on MSN such as Seb) and actually a Spike should have a pre-requisite on a fair amount of Research before heading down the hacking route.

By the way,I wholeheartedly recommend the WPF articles written by Yazan Diranieh.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Seen in the wild.

clock October 22, 2008 06:30 by author daniel

It looks like I too had some fun just like Seb (http://serialseb.blogspot.com/2008/10/while-im-in-ranting-mood.html) when I saw this in production code:

 

/// <summary>
/// This is a sample class showing you how to {…NDA…}
/// </summary>
public class Controller : IController 
{

}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


RTFM #1 : TDD

clock September 24, 2008 07:38 by author daniel

I have in the past been subject to agile developers who claimed with tremendous fervor that Test-Driven Development (http://en.wikipedia.org/wiki/Test-driven_development)  is the only proven agile development technique.

It’s not in the name, but Test-Driven Development importantly commands that tests are written before the code it is supposed to test. The direct benefits of this depend upon the kind of tests we’re writing.

This brings me to something that I find irritating and that’s the disproportionate focus on Unit Tests as the kind of tests to use when one talks about TDD. Unit Tests (http://en.wikipedia.org/wiki/Unit_testing) sure help us design better code but as someone put it before, Unit Testing allows the developer write good code (Separation of Concerns, Single Responsibility Principle, and many more) but Unit Testing doesn’t necessarily help you to write the right code, by right code it is meant the code that is directly involved in fulfilling a functional requirement.

Now coming back to the RTFM material, re-reading the definition of TDD in Wikipedia I noticed a paragraph that talks about Acceptance Test-Driven Development (ATDD) and about Unit Test-Driven Development (UTDD). The first technique is about writing tests that prove that the system fulfills all its functional requirements, the second one being about writing tests that prove that parts of the system work independently from others. In some ways, one can say that ATDD is a holistic technique to development with UTDD as its counterpart as a reductionist one.

So, assuming that the formula TDD = ATDD + UTDD is assumed when one talks about Test-Driven Development then I’m all for TDD without the shadow of a doubt.

I’d like to finally add that there is a great TDD book that is available as a Work In Progress and it can be found here : http://www.mockobjects.com/book/
Notice the notion of Inner (Unit Testing) and Outer (Acceptance Testing) feedback loops in TDD.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


RecentPosts

Sign in