简体   繁体   中英

C# Unit Testing - Generating Mock DataContexts / LINQ -> SQL classes

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

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.

我知道的最好的方法是提取这个对象的接口并使用它来创建模拟对象,所以如果你使用linqtosql或EF与数据库交谈,或者你根本不和任何数据库交谈,那真的无关紧要。

[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

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 (ie Linq expression trees) and C# 3.0 features (ie 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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM