views:

337

answers:

4

Hi All,

I am loving the new world that is C#, I've come to a point with my toy programs where I want to start writing some unit tests.

My code currently uses a database via a DatabaseDataContext object (*.dbml file), what's the best way to create a mock for this object? Given how easy it is to generate the database LINQ -> SQL code and how common a request this must be I'm hoping that VS2010 has built in functionality to help with testing.

If I'm way off and this must be done manually could you please enlighten me as to your preferred approach?

Many Thanks,

Gavin

+3  A: 

The best way I know is to extract this object's interface and use that to create the mock object, so it really won't matter if you use linqtosql or EF to talk to the database, or if you talk to any database at all.

Otávio Décio
Except that you can't switch out an implementation of L2S for EF, as they both generate models that are incompatible with each other. Leaky abstractions are leaky.
Will
@Will - good point.
Otávio Décio
A: 

Few things which might be useful for you:

Moq (pronounced "Mock-you" or just "Mock") is the only mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, type-safe and refactoring-friendly mocking library available. And it supports mocking interfaces as well as classes. Its API is extremely simple and straightforward, and doesn't require any prior knowledge or experience with mocking concepts.

LINQPad lets you interactively query databases in a modern query language: LINQ. Kiss goodbye to SQL Management Studio!

LINQPad supports everything in C# 3.0 and Framework 3.5, and more:

LINQ to Objects LINQ to SQL and Entity Framework LINQ to XML WCF Data Services & SQL Azure LINQ to SQLite and MySQL Enterprise Server Mindscape LightSpeed ORM (Even old-fashioned SQL!)

Lukas Šalkauskas
+1  A: 

[Disclaimer: I work at Typemock]

You can use Typemock Isolator to create a fake object and set it's methods to return what you need:

var fakeContext = Isolate.Fake.Instance<DatabaseDataContext>();

Take a look at this blog post on how to fake Linq2Sql: Faking LINQ to SQL DataContext Tables with Isolator

Dror Helper
+3  A: 

The problem with the DataContext is that it isn't designed for mocking.

A free tool for mocking the unmockable is Moles from Pex (Pex moles?). Its roughly equivalent to TypeMock.

Will