Use a generator to test that pesky DataContext

There has been a lot of buzz about how exactly to get around the issues of testing the DataContext in LINQ to SQL.  I've seen a lot of good blog posts explaining very good solutions to the problem.  But so far I have yet to see a total solution written up yet.

The first thing I set out to do was create an ITable<T> interface, and a TableProxy<T> class so that I could properly wrap the Table<T> objects which come on a DataContext.

I created a simple class which takes a Table<T> into its constructor then simply passes through to the methods on that Table, this class implemented my new interface and voila.  Simple enough?  I also decided to make a TableFake<T> which would simply insert and remove from a predefined list, that way I could save myself a little work stubbing out ITable<T> for all of my tests.

Proxy Generation

The next trick was to create my IXXXDataContext and XXXDataContextProxy.  But this wasn't something I wanted to have to update manually every single time we added a new table or function call to the generated data context.  I started sifting through the DBML generated Xml file that is created to keep track of all the important database artifacts before creating the actual DataContext file itself.  It looked like it would be pretty simple to put together a small console application that could read this file, and spit out the interface and proxy into one file as partial's.

Testing Magic

The beauty of this approach can best be seen in the tests written against it.  Consider the following code:

public class SomeClass
{
    public IDataContext Context { get; set; }

    public void SaveBook(Book book)
    {
        if (book.IsNew)
           Context.Books.InsertOnSubmit(book);
        else
           Context.Books.Attach(book, true);
        Context.SubmitChanges();
    }
}

With your typical DataContext, the only way to test this would be if you were willing to actually save to some kind of database.  After generating the proxy however.  Our test will look as follows:

public class When_saving_a_new_book : Specification
{
    private IDataContext _context;
    private SomeClass _someClass;

    protected override Before_each_spec()
    {
        _context = Mock<IDataContext>();
        _context.Stub(o => o.Books).Return(new TableFake<Book>(new List<Book>()));
        _someClass.Context = _context;
        Mocks.ReplayAll();
    }

    public void Then_submit_changes_should_be_called()
    {
        _someClass.Save(new Book());
        _context.AssertWasCalled(o => o.SubmitChanges());
    }

    public void Then_the_new_book_should_be_added_to_the_table()
    {
        var _book = new Book();
        _someClass.Save(_book);
        _context.Books.Count().ShouldBe(1);
        _context.Books.ShouldContain(_book);
    }
}

All of the code for the TableProxy<T>, ITable<T>, TableFake<T> and the generator application can be found in the CodeIncubator samples on Google Code.  Feel free to use this information as you see fit and let me know what you think.

Get the Code!

Why do I need resharper?

I thought that I'd put together this blog explaining some of the most useful benefits I've found as a long time user of Visual Studio without and extra bells and whistles of a third party refactoring plugin.

One of the nicer features that I make extensive use of in my current project (which is a solution with 19 projects and probably near a thousand different classes) is the Camel Cased type and method search.  Instead of opening up the solution explorer and sifting through a long list of files, I can simply hit Ctrl-T and type the upper case letters of the class I need.  If I want to see the CustomFieldDesignerViewController class, I start typing, C-F-D-V-C and the list of matches will be reduced to only those who have upper case letters in that order.  The same "Camel Hump Casing" that applies to the type search also applies to the method search, and to the intellisense.  When I want a line that says:

CustomSomethingDropDownList x = value;

All I have to do is type C-S-D-D-L and the intellisense will be automatically filtered to only the things which match that camel casing.  The saves an incredible amount of time with typing by allowing the correct items to be selected faster than having to type out the first maybe 10+ characters to get to what you want (esspecially on projects when a lot of the classes start with the same first names, etc)

The second thing that has come in extremely useful that resharper does is that it finds "illogical" logic.  For instance, if I were to say:

If (x == 1)
{
}
else if (x ==1)
{
}

Resharper will highlight this else and explain that this will never happen.  Now in my example this is clearly very easy to see from reading it.  But imagine if you had a series of if/else statements with more complicated logic.  It's very useful to be able to detect these because it typically points out a mistake in a branch of the logic as opposed to a useless section.  This saves an immeasurable amount of time by helping proactively identify bugs before they become bugs.

The highlighting that comes with Resharper is also extremely more detailed then what comes standard with Visual Studio.  Now a lot of people would argue that this highlighting is unnecessary.  It points out a lot of issues which range from "hints" to "errors".  Errors that might otherwise not show up until trying to compile (and compiling a 19 project solution is no small amount of time).  The best part about these issues is that with a simple click of ctrl-enter resharper can typically fix most errors for you.  This also has the added benefit of teaching programmers if they have a habit of doing something that is in reality, unnecessary.  It also helps large groups come up with standards (as resharper's hints and errors are configurable) that everyone can agree to follow.

These are just a few of the many benefits, I'd feel remiss if I didn't at least mention the enhanced refactoring support, enhanced template support, and automated using inserting (for extension methods, which visual studio does not yet support).

Take a look at the Re-sharper 4.0 EAP's if you can, it's certainly worth checking out.

LINQ vs Methodized Syntax

Recently we had a debate about which way we prefer to see Linq syntax written.  In the LINQ from/select syntax below:

Linq Code

Or, in the Methodized syntax which follows:

Methodized Syntax

I personally prefer the more methodized syntax where it can be used typically (esspecially when the statement contains only a simple where clause).  However it is worth noting that the Join method which takes in four seperate parameters is quite painful to write against, the inferred generics do not properly pick up what you are working with until you finish the entire statement.  I threw together a more "english friendly" syntax which also has the added benefit of allowing generics to properly infer at each step of the way.

Finished Syntax

Now granted some people will argue this syntax takes up "more lines", you could put some of these method calls onto one line if you felt it really necessary.  I've included the small sample of source code which you can get here.