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!

Print | posted @ Monday, July 14, 2008 9:35 PM

Comments on this entry:

Gravatar # re: Use a generator to test that pesky DataContext
by Question at 8/5/2009 2:34 PM

I have a web application, on .NET 3.5, I use Linq to SQl, I used the ContextInterfaceGenerator to generate the Interface, lets call my .dbml file DB.dbml and the Interface generated as IDBDataContext. Do I have to make changes to the DB.designer.vb auto-generated file to inherit the IDBDataContext? Otherwise how will I be able to use the real dbml instance in my code?
Gravatar # re: Use a generator to test that pesky DataContext
by Wesley at 10/27/2010 12:11 PM

Thank you soo much! This tip is super useful!
Gravatar # re: Use a generator to test that pesky DataContext
by Shutterfly at 12/30/2010 11:24 AM

Appreciate the code, worked like a charm. DataContext no longer a pain..

medical assistant training
Gravatar # re: Use a generator to test that pesky DataContext
by slots en ligne at 6/11/2011 4:19 AM

This facility makes it the most versatile and explicit means of communication yet devised for quick mass appreciation
Gravatar # link building services
by link building services at 6/16/2011 6:35 AM

Well, this is my first visit to your blog. And I feel great here. I like your blog and content here. Keep on posting such an interesting post.
Gravatar # re: Use a generator to test that pesky DataContext
by Giochi casino at 6/17/2011 8:47 AM

I want to express my admiration of your writing skill and ability to make reader to read the while thing to the end.
Gravatar # re: Use a generator to test that pesky DataContext
by Kindle Review blog at 6/22/2011 5:16 PM

It is a very good example for a beginner like me. Thanks a lot.
Gravatar # re: Use a generator to test that pesky DataContext
by online casino at 7/11/2011 7:09 AM

I will be subscribing to your feed and I hope you post again soon. Admiring the time and effort you put into your blog.
Gravatar # re: Use a generator to test that pesky DataContext
by Free Credit Report at 7/13/2011 12:40 PM

Simple but it works. Thank for sharing.
Gravatar # re: Use a generator to test that pesky DataContext
by BlackBerry Triton at 7/16/2011 9:17 AM

Very nice! It would be great if you could continue this series with examples. Thanks for the publishing codes.
BlackBerry 4G phone
BlackBerry 4G smartphone
Gravatar # re: Use a generator to test that pesky DataContext
by motor trade insurance at 7/19/2011 9:18 AM

I will bookmark your blog and have my friends check up here often. I am quite sure they will learn lots of new stuff here than anybody else. Thanks for sharing this information.
Gravatar # re: Use a generator to test that pesky DataContext
by Online Credit Card at 7/27/2011 7:25 AM

One could find some piece of useful information about online credit card on the following links:

Online Credit Card
Online Credit Card Application
Online Credit Card Fraud
Online Credit Card Generator
Online Credit Card Payments
Online Credit Card Processing
Online Credit Card Processing Services
Gravatar # re: Use a generator to test that pesky DataContext
by steel trader at 7/27/2011 1:26 PM

There are a lot of great points here, but I'm not sure I agree with real-time search being discarded. I agree that it's not very relevant,but isn't the point of it to show what people are currently saying about a topic.
Gravatar # re: Use a generator to test that pesky DataContext
by cna certification at 8/8/2011 1:25 AM

DataContext file is giving some error.
Gravatar # re: Use a generator to test that pesky DataContext
by viagra generique at 8/15/2011 10:22 AM

Are you presently tired of trying to find photos and video clip of other people having all of the excitment? I have discovered live Asian web cams that you direct the actions. Nothing at all is as stimulating as interactive online chat.
Gravatar # re: Use a generator to test that pesky DataContext
by super cars at 9/6/2011 12:05 PM

these tricks are simply awesome... love them <3 ..keep posting such articles n tricks :)
Gravatar # 2 Day Diet Japan Lingzhi Slimming Formula
by 2daydiet at 9/8/2011 11:49 PM

The study doesn't prove that moderate drinking will lead to better health compared to not drinking, since it's possible that other factors could account for the difference. Also, the research doesn't examine the long-term cost of drinking, say, wine instead of milk with dinner.
2 day diet
2 day diet pills
2 day diet pill
2 day diet lingzhi
two day diet
2 days diet japan
2 days diet
2 days diet japan lingzhi
2 day japan lingzhi slimming formula
lingzhi 2 day diet pills
Gravatar # re: Use a generator to test that pesky DataContext
by WashingtonMary24 at 9/14/2011 3:41 PM

That's known that money makes people disembarrass. But what to do when somebody doesn't have money? The one way is to get the loans or just auto loan.
Gravatar # A pharmacist at the <a href="http://www.sourcevan.com/meizitang-botanical.html">Meizitang Botanical Slimming Soft Gel</a> in Ham
by source at 9/23/2011 1:49 AM

A pharmacist at the Meizitang Botanical Slimming Soft Gel in Hamilton said a 2 day diet nurse fruta planta administers the flu Zhen De Shou shots Zhen De Shou Fat Loss Capsules in Liji Shou the store. She said the nurse gives about 10 to 15 vaccinations a day and Lida Daidaihua Slimming will Pai You Ji be in http://www.sourcevan.com store through Sept. 24.
Gravatar # re: Use a generator to test that pesky DataContext
by jaguar xc16 at 10/1/2011 2:02 PM

using a generator to test is very useful... i really appreciate thsi post...keep posting such articles
Gravatar # re: Use a generator to test that pesky DataContext
by Awir at 10/2/2011 5:29 AM

Very interesting website with useful articles, thanks to have shared Getting Free Credit Report
Gravatar # re: Use a generator to test that pesky DataContext
by pay for essays at 10/6/2011 12:34 AM

Are you dreaming about academic grades? Do not know how to begin your essay papers completing? That is not a problem! You can get information: "how to do my essay " and relax!
Gravatar # re: Use a generator to test that pesky DataContext
by buy custom essay papers at 10/8/2011 5:50 AM

It was hands-down to buy essays and lots of students don’t get know that such really smart content connected with this good postcan exists and because of that students buy term paper.
Gravatar # re: Use a generator to test that pesky DataContext
by dissertation writing at 10/8/2011 6:22 AM

People would like to receive a good degree, but what is the right way to have this? We will offer to notice for the thesis writing service to buy the example of thesis about this good topic at. I used it and had got good grade.
Gravatar # re: Use a generator to test that pesky DataContext
by kindle 4 at 10/9/2011 7:16 AM

Good to hear about this topic...informative content..
Gravatar # re: Use a generator to test that pesky DataContext
by Social Media Optimization at 10/11/2011 9:44 AM

I Just try your tip for my recent project.....And what it is working...thanks
Gravatar # re: Use a generator to test that pesky DataContext
by french riviera at 10/12/2011 5:38 PM

You got a really useful blog I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me.
Gravatar # re: Use a generator to test that pesky DataContext
by seo backlink at 10/13/2011 7:20 AM

You should be an expert in order to make your PR high. Other way you will need to use SEO at cheap seo packages providers. If you did not hear about it then you would be able to read about that in the internet!
Gravatar # hp pavilion dv6
by hp pavilion dv6 at 10/14/2011 10:26 AM

very good
Gravatar # good
by Atlanta escorts at 10/15/2011 9:05 AM


The data is extremely helpful to my needs and i have find solution just after i implemented your ideas.
Gravatar # re: Use a generator to test that pesky DataContext
by write my essays at 10/15/2011 4:38 PM

Your academic career isn't an issue you can play games with! Hence, you must treat it very seriously. Good custom writing service seems to be a proper place to buy essay online and secure your reputation.
Gravatar # re: Use a generator to test that pesky DataContext
by buy thesis at 10/15/2011 4:42 PM

We will take dissertation writing or history dissertation. And to display that you are real professional, you have to take a thesis.
Gravatar # re: Use a generator to test that pesky DataContext
by custom essays at 10/17/2011 7:50 AM

The essay writing just about this topic, you would see at the writing service. Order the research papers and custom essay just about this post.
Gravatar # re: Use a generator to test that pesky DataContext
by buy custom essay papers at 10/17/2011 8:05 AM

Different men have to solve different difficulties such as toxic waste. All these problems are not easy to cope with. Nevertheless, when you have academic papers writing problems, you will have nothing to worry about. You should just buy essay and solve your troubles.
Gravatar # re: Use a generator to test that pesky DataContext
by article submit at 10/18/2011 5:50 PM

Don’t waste your time, use the support of article submission and article submission guide and present your good enough theme just about this post fast.
Gravatar # Dell – Inspiron Mini Netbook Obsidian Black
by Dell – Inspiron Mini Netbook Obs at 10/20/2011 6:35 AM

thanx admin
Gravatar # re: Use a generator to test that pesky DataContext
by Play Blackjack Online at 10/25/2011 4:33 AM

Thanks for summation of information on the topic about DataContext. I have tried several ways and I can say now that your code maybe the simplest.
Gravatar # onetime credit report
by onetime credit report at 10/26/2011 7:52 AM

hi fine
Gravatar # online credit card
by online credit card at 10/26/2011 7:59 AM

nice thanx
Gravatar # re: Use a generator to test that pesky DataContext
by credit card debt relief at 10/26/2011 8:01 AM

credit card debt relief
Gravatar # re: Use a generator to test that pesky DataContext
by free credit advisor at 10/26/2011 8:03 AM

free credit advisor
Gravatar # re: Use a generator to test that pesky DataContext
by poor credit card at 10/26/2011 8:04 AM

nice
Gravatar # re: Use a generator to test that pesky DataContext
by get free annual credit report at 10/26/2011 8:05 AM

get free annual credit repor
Gravatar # re: Use a generator to test that pesky DataContext
by bad credit refinance at 10/26/2011 8:07 AM

nice on
Gravatar # re: Use a generator to test that pesky DataContext
by renters insurance at 10/26/2011 8:09 AM

renters insurance
Gravatar # re: Use a generator to test that pesky DataContext
by credit card with bad credit at 10/26/2011 8:10 AM

credit card with bad cred
Gravatar # re: Use a generator to test that pesky DataContext
by get free credit score at 10/26/2011 8:12 AM

get free credit scor
Gravatar # re: Use a generator to test that pesky DataContext
by no credit check loans at 10/26/2011 8:13 AM

no credit check loa
Gravatar # re: Use a generator to test that pesky DataContext
by internet filter at 10/26/2011 8:14 AM

internet filte
Gravatar # re: Use a generator to test that pesky DataContext
by 3 free credit reports at 10/26/2011 8:16 AM

3 free credit reports
Gravatar # re: Use a generator to test that pesky DataContext
by cell phone plans at 10/26/2011 8:17 AM

cell phone plans
Gravatar # re: Use a generator to test that pesky DataContext
by free web hosting at 10/26/2011 8:19 AM

free web hosting.
Gravatar # re: Use a generator to test that pesky DataContext
by business plans at 10/26/2011 8:20 AM

business plans
Gravatar # re: Use a generator to test that pesky DataContext
by seasonal allergies at 10/26/2011 8:23 AM

seasonal allergie
Gravatar # re: Use a generator to test that pesky DataContext
by dental insurance at 10/26/2011 8:23 AM

dental insurance
Gravatar # re: Use a generator to test that pesky DataContext
by contact lens at 10/26/2011 8:25 AM

contact lens
Gravatar # re: Use a generator to test that pesky DataContext
by stop smoking at 10/26/2011 8:25 AM

stop smoking
Gravatar # re: Use a generator to test that pesky DataContext
by loans with bad credit at 10/26/2011 8:26 AM

loans with bad credit
Gravatar # re: Use a generator to test that pesky DataContext
by office furniture at 10/26/2011 8:28 AM

office furniture
Gravatar # re: Use a generator to test that pesky DataContext
by how to improve credit score at 10/26/2011 8:29 AM

how to improve credit score
Gravatar # re: Use a generator to test that pesky DataContext
by Botox Auckland at 10/28/2011 1:58 AM

Hi, this one is great and is really a good post. I think it will help me a lot in the related stuff and is very much useful for me. Very well, written I appreciate & must say good job..
Gravatar # free credit report no credit card
by free credit report no credit car at 11/2/2011 12:55 AM

thanx free credit report no credit card
Gravatar # poor credit card
by poor credit card at 11/2/2011 1:37 AM

nice admin
poor credit card
Gravatar # re: Use a generator to test that pesky DataContext
by Barcode generator at 11/3/2011 7:10 AM

I am so grateful to read this wonderful post. Thank you for discussing this great topic. I really admire the writer for allotting their time for this impressive article. Thank you.
Gravatar # re: Use a generator to test that pesky DataContext
by Marijuana test at 11/4/2011 8:41 AM

I have read Many of your Recent Blogs, Your blog topics are very
informative and useful,
Thanks for posting such topics
Gravatar # re: Use a generator to test that pesky DataContext
by pacquiao vs marquez at 11/5/2011 10:59 AM

There aren't enough days in the weekend.
Gravatar # re: Use a generator to test that pesky DataContext
by gps reviews at 11/9/2011 1:55 AM

We are very much thrilled with the contents you may have mentioned. I enjoyed every tiny bit some of it. It includes truly information. I need to appreciation for this informative read; I really appreciate sharing this excellent.
Gravatar # kindle fire black friday
by kindle fire black friday at 11/12/2011 3:53 AM

kindle fire black friday
Gravatar # Kindle Black Friday 
by Kindle Black Friday  at 11/14/2011 10:30 AM

rrrKindle Black Friday 
Gravatar # Kindle Black Friday 
by Kindle Black Friday  at 11/14/2011 10:37 AM

aaxKindle Black Friday 
Gravatar # Kindle Black Friday 
by Kindle Black Friday  at 11/14/2011 11:05 AM

vvvcKindle Black Friday 
Gravatar # Kindle Black Friday 
by Kindle Black Friday  at 11/14/2011 11:18 AM

bbbbKindle Black Friday 
Gravatar # Android app developers
by Android app developers at 11/16/2011 4:15 AM

Thanks for creating this interesting blog and its the great resourceful information for lots of internet users. so you can create more blog with useful message.
Gravatar # re: Use a generator to test that pesky DataContext
by Career coach at 11/16/2011 6:21 AM

I simply started reading your posting and just after couple of seconds, I uncovered it fascinating. I read you’re mostly all of the posts. Nice posts, many thanks for sharing the posts effortlessly.
Gravatar # black friday kindle fire
by black friday kindle fire at 11/16/2011 12:36 PM

black friday kindle fire
Gravatar # black friday kindle fire
by black friday kindle fire at 11/16/2011 12:40 PM

black friday kindle fire
1
Gravatar # kindle touch black friday
by kindle touch black friday at 11/16/2011 12:46 PM

2 kindle touch black friday
2
Gravatar # Thesis
by Thesis at 11/17/2011 11:23 AM

Nice Buddy
Thesis Paper
Gravatar # www.watchcasinos.com
by www.watchcasinos.com at 11/22/2011 9:59 PM

The first two paragraphs are explained so nicely that I enjoy reading the blog. And want to read only your blog from the internet. Keep explaining us through the blog like this.
Gravatar # re: Use a generator to test that pesky DataContext
by truck accident lawyer at 11/30/2011 10:07 PM

I just wanna say thank you for the information that you have been shared to us readers. Thanks for posting this kind of theme.
Gravatar # re: Use a generator to test that pesky DataContext
by Aluminum Sheet at 12/8/2011 1:41 AM

I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand how to make comedy tour. Thank you for the post.
Gravatar # gu10 led bulbs
by gu10 led bulbs at 12/9/2011 7:19 AM

The insight that you provide is excellent. The content is extremely interesting, you provoke thinking and the page layout is eye catching. I have bookmarked this blog and look forward to reading more. Thanks for posting and keep up the good work
Gravatar # re: Use a generator to test that pesky DataContext
by Saliva drug tests at 12/15/2011 2:14 AM

Impressive article, the content is very helpful thanks for sharing. Thanks also to the generosity of the people behind this post. Keep it up!
Gravatar # re: Use a generator to test that pesky DataContext
by Mobile software development at 12/16/2011 6:42 AM

Wonderful post -Thanks for sharing this article with me and your reader. I have add your site to my bookmark for search any more article that I am search then I come for your site first for search.
Gravatar # re: Use a generator to test that pesky DataContext
by loans at 12/25/2011 2:17 AM

Set your own life more simple take the personal loans and all you require.
Gravatar # re: Use a generator to test that pesky DataContext
by Tiffany Co at 12/26/2011 9:56 PM

Tiffany & co There have been lots of people within the target audience from Town Vineyard down-town a week ago that appreciated the actual Ur-Marianne, louis vuitton handbags the actual timid 17-year-old that experienced tiptoed the woman's method to stardom upon the effectiveness of which tune, Tiffany jewelry compiled by the love-struck Mick Jagger, along with Keith Richards. burberry scarf As well as a lot have been fascinated through the timeworn picture from the fairly, Tiffany rings convent-educated waif within ribbons as well as purple velvet plucked in the stores associated with King’s Street.
cheap louis vuitton handbags Other people replied much more warmly towards the midlife Microsoft. Faithfull performing “Broken British, ” Tiffany necklace the actual intense anthem which signaled the woman's resurrection at the conclusion from the ’burberry scarf sale seventies from the 10 years associated with drug-induced exile.
It had been the tired, burberry cashmere scarf as well as cautious, Microsoft. Faithfull that shattered through rehearsals in the Gibson Acoustic guitar Galleries within Midtown a week ago in order to reminisce. Tiffany jewelry set However, you wouldn't possess known as the woman's frail.
Gravatar # re: Use a generator to test that pesky DataContext
by Teen Psychologist at 12/27/2011 12:07 AM

There is obviously far more to know about it as I expected. I like to stress that it have made some good points in this posting.
Every teenage child faces some or the problem in his/her teenage. And if they don’t get right guidance they tend to fall on wrong path. So to give right guidance there are teen psychologist who can give their teenage kids right suggestion. Christian heart counseling can help in getting right psychologist for teenagers. For more details visit http://christianheartcounseling.com/
Gravatar # re: Use a generator to test that pesky DataContext
by Alec Jones at 1/1/2012 3:47 PM

If you have a problem identifying an unknown wireless call, you can choose to do a Cell Phone Lookup. also known as a Reverse Phone Lookup, or a Reverse Cell Phone Lookup, it can easily be done online, whether you want to search for the owner of a Verizon Reverse Phone Lookup or a Sprint Reverse Phone Lookup . I also know this can be considered something like a Cell Phone White Pages Plus, it's always a good idea to have the Outdoor Lighting turned on outside in your yard and the Pellet Stoves ready to heat the home.
Gravatar # re: Use a generator to test that pesky DataContext
by 2013 calendar at 1/7/2012 4:27 AM

2013 calendar
Gravatar # re: Use a generator to test that pesky DataContext
by 2012 calendar at 1/7/2012 4:31 AM

2012 calendar
.
Gravatar # re: Use a generator to test that pesky DataContext
by one time credit report at 1/7/2012 4:34 AM

nice
one time credit report
Gravatar # re: Use a generator to test that pesky DataContext
by joomla development at 1/10/2012 2:00 AM

This post is really sweetest on this notable topic. I harmonise with your conclusions and will thirstily look forward to your incoming updates. Keep posting good blogs. Thanks.
Gravatar # re: Use a generator to test that pesky DataContext
by Buy life insurance at 1/11/2012 3:37 AM

I just stumbled upon your blog and wanted to say that I have really enjoyed surfing around your blog posts. After all I’ll be subscribing to your feed and I hope you write again soon!
Gravatar # louis vuitton uk
by louis vuitton uk at 1/16/2012 1:49 AM

louis vuitton uk http://www.louisvuitton-ukoutlets.org.uk
Gravatar # coach outlet online
by coach outlet online at 1/16/2012 1:50 AM

coach outlet online te again soon!
Gravatar # re: Use a generator to test that pesky DataContext
by coach factory outlet at 1/16/2012 3:35 AM

coach factory outlet
Gravatar # re: Use a generator to test that pesky DataContext
by coach outlet online at 1/16/2012 3:36 AM

coach outlet online
http://www.coachoutletonlinecoachusa.com
Gravatar # re: Use a generator to test that pesky DataContext
by Adele_uk at 1/16/2012 9:59 AM

Consultants bridal stores will long evening dresses for sale gladly help you evening long dresses in a good pre-holiday rush: we provide a broad array of wedding ceremony dresses in USA well-known global brands. The optimal combination of price and quality from the marriage ceremony gown is assured!
Gravatar # re: Use a generator to test that pesky DataContext
by Jannat at 1/20/2012 6:50 AM

The best part of this whole approach is information gathering. People from almost any part of the world has a fetish for enriched knowledge, this makes them get a better peak inside the mind of any nation's culture or heritage.
Gravatar # re: Use a generator to test that pesky DataContext
by jhan at 1/22/2012 9:08 AM

thanks this is very usefull tips...venapro
Gravatar # re: Use a generator to test that pesky DataContext
by Web Design Quote at 1/25/2012 12:19 AM

This is really one of the great post! I love all this information very well. I have learn good knowledge here so I feel very happy!
Gravatar # re: Use a generator to test that pesky DataContext
by baby bath tub at 1/25/2012 11:09 AM

Thanks for this amazing tips on testing the DataContext in LINQ to SQL. I've always had serious issues.
Gravatar # re: Use a generator to test that pesky DataContext
by baby strollers at 1/25/2012 11:14 AM

Amazing skill of explaining, makes it sound and look so easy. Thanks anyway for helping to simplify. Baby monitor
Gravatar # cheap dvd box set
by cheap dvd box set at 1/31/2012 1:52 AM

Buy The

Big Bang Theory Seasons 1-5 DVD box set
for free shipping.
Gravatar # cheap dvd box set
by cheap dvd box set at 1/31/2012 2:45 AM

Do you like watching DVD movies and tv show ?We have many
Cheap DVD box set with unique style,such as True Blood Season 1-4 and
Desperate Housewivies Season 1-8.
Gravatar # re: Use a generator to test that pesky DataContext
by moonshine at 1/31/2012 11:07 AM

chichen itza The seven World Wonders list of the ancient times was initially recorded approximately in the 2nd century BC. 

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 4 and 5 and type the answer here: