1

Currently i am writing unit tests for repository, wrapping linq2db methods. I am trying to mock a simple select method but of course you can't mock extension methods like GetTable() or Insert(item).

What i am currently trying to do is set up a simple test using Moq, AutoFixture and Autofac

using (var mock = AutoMock.GetLoose())
{
     var fixture = new Fixture();
     var customers = fixture
        .Build<List<Customer>>()
        .Create();

     mock.Mock<IDataContext>()
        .Setup(item => item.GetTable<Customer>().ToList())
        .Returns(customers);

     var cls = mock.Create<CustomerRepository>();

     var actual = cls.GetAllAsync().Result;

     Assert.IsTrue(actual != null);
     Assert.Equals(customers.Count, actual.Count());
}

The test of course fails at Setup, since GetTable<Customer>() is an extension method of IDataContext.

How do you properly test a repository wrapping linq2db?

  • Possible duplicate of [Mocking Extension Methods with Moq](https://stackoverflow.com/questions/2295960/mocking-extension-methods-with-moq) – Aleks Andreev Apr 04 '19 at 10:57
  • @AleksAndreev it is a 'yes' regarding mocking extension, but a 'no' since i am using a 3rd party extension, wheres i can't extend the helper class in order for it to be mock-able. – Crovean Vlad Apr 04 '19 at 11:01
  • @CroveanVlad Then you will need to encapsulate the code that calls the 3rd party extension behind an abstraction that you control. That way you can replace any tight coupling with your on implementations. – Nkosi Apr 04 '19 at 11:28
  • Is it worth doing additional layer? Or is it easier and better to have a test database with test data and run unit tests with its data? – Crovean Vlad Apr 04 '19 at 11:35
  • 1
    that then becomes an integration test. As for whether it is worth it, that is a matter of opinion. My view is that the difficultly of testing code is directly related to the quality of the design of the code. Try following SOLID principles. – Nkosi Apr 04 '19 at 11:37
  • Check this discussion https://github.com/linq2db/linq2db/issues/387#issuecomment-441367477 –  Apr 05 '19 at 06:59

0 Answers0