Aug
19

Mocking Linq – Preview

Author Eli Lopian    Category Product     Tags

We are working on our .NET 3.5 Support. There are many new feature that have been added, we will take a look at how to mock a linq statement

For the following code in our application

Northwind db = new Northwind(connStr) ; var query = from c in db.Customers where c.City == "Sarasota" select new { c.Name, c.City };

Here is how to mock this statement and return fake customers

[TestMethod] [VerifyMocks] public void IsolateLinq() { // create fake return values var fake = new[] { new {Name="Fake 1",City="NY"}, new {Name="Fake 2",City="London"}}; using (RecordExpectations r = new RecordExpectations()) { // don't hit the database, instead return test customers Northwind db = new Northwind(connStr) ; var answer = from c in db.Customers where c.City == "not-used" select new { c.Name, c.City }; r.Return(fake); } CallClassUnderTest(); // Continue with test }

Comments about this syntax are welcome

Bookmark and Share

4 Comments to “Mocking Linq – Preview”

  • Larry-K December 31, 2007 at 7:31 am

    Can this Mocking Linq be done with the community version, or is a higher level required?

  • Eli Lopian December 31, 2007 at 9:00 am

    Larry,
    The Enterprise Edition is required for Linq.

  • Assaf Stone January 24, 2008 at 6:27 pm

    This is not true!

    Linq can be mocked with the community version.

    All you need to do is mock [Your]DataContext, and pass an IQueryable instead of your Table property (Use ExpectGetAlways(propertyName, mockList.AsQueryable()).

    HTH,
    Assaf.

  • lola March 6, 2008 at 8:12 pm

    interesting post thx