How are people unit testing code that uses Linq to SQL

后端 未结 7 823
生来不讨喜
生来不讨喜 2021-01-30 06:24

How are people unit testing code that uses Linq to SQL?

7条回答
  •  不思量自难忘°
    2021-01-30 06:56

    3 years late, but this is how I do it:

    https://github.com/lukesampson/LinqToSQL-test-extensions/

    No need to write a wrapper or do lots of plumbing, just drop the T4 template next to your .dbml and you get:

    1. An interface for your data context e.g. IExampleDataContext
    2. An in-memory mock for your data context e.g. MemoryExampleDataContext

    Both will automatically use the mappings you've already configured in your DBML.

    So you can do things like

    public class ProductRepo {
        IExampleDataContext DB { get; set };
        public ProductRepo(IExampleDataContext db) {
            DB = db;
        }
    
        public List GetProducts() {
            return DB.Products.ToList();
        }
    }
    

    and you can call that with either

    new ProductRepo(new MemoryExampleDataContext()).GetProducts(); // for testing
    

    or

    new ProductRepo(new ExampleDataContext()).GetProducts(); // use the real DB
    

提交回复
热议问题