Unit testing with queries defined in extension methods

后端 未结 8 727
执笔经年
执笔经年 2020-12-23 02:16

In my project I am using the following approach to querying data from the database:

  1. Use a generic repository that can return any type and is not bound to one t
相关标签:
8条回答
  • 2020-12-23 03:13

    To isolate testing just to just the extension method i wouldn't mock anything. Create a list of Invoices in a List() with predefined values for each of the 3 tests and then invoke the extension method on the fakeInvoiceList.AsQueryable() and test the results.

    Create entities in memory in a fakeList.

    var testList = new List<Invoice>();
    testList.Add(new Invoice {...});
    
    var result = testList().AsQueryable().ByInvoiceType(enumValue).ToList();
    
    // test results
    
    0 讨论(0)
  • 2020-12-23 03:19

    If it suits your conditions, you can hijack generics to overload extension methods. Lets take the following example:

    interface ISession
    {
        // session members
    }
    
    class FakeSession : ISession
    {
        public void Query()
        {
            Console.WriteLine("fake implementation");
        }
    }
    
    static class ISessionExtensions
    {
        public static void Query(this ISession test)
        {
            Console.WriteLine("real implementation");
        }
    }
    
    static void Stub1(ISession test)
    {
        test.Query(); // calls the real method
    }
    
    static void Stub2<TTest>(TTest test) where TTest : FakeSession
    {
        test.Query(); // calls the fake method
    }
    
    0 讨论(0)
提交回复
热议问题