在C#中使用Moq和SQLiteConnection

时间:2015-08-12 12:24:05

标签: c# .net sqlite nunit moq

我试图了解如何将Moq与SQLiteConnection一起使用。 问题是因为我对Moq很新,而且我没有找到任何关于我的问题的相关教程。

我想了解如何使用它的一些提示。

错误:

    SetUp : Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: SQLite.Net.SQLiteConnection.
    Could not find a constructor that would match given arguments:
    SQLite.Net.Platform.Win32.SQLitePlatformWin32
    System.String
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance(Type proxyType, List`1 proxyArguments, Type classToProxy, Object[] constructorArguments)
   at Moq.Proxy.CastleProxyFactory.CreateProxy(Type mockType, ICallInterceptor interceptor, Type[] interfaces, Object[] arguments)
   at Moq.Mock`1.<InitializeInstance>b__2()
   at Moq.Mock`1.OnGetObject()
   at Moq.Mock`1.get_Object()
   at Silje.Synchronization.Test.AktoerSynchronizationTest.SetUp()

代码示例:

        private SQLiteConnection _sqLiteConnection;

        [SetUp]
        public void SetUp()
        {
            Mock<SQLiteConnection> 
            mockSQLiteconnection = new Mock<SQLiteConnection>(MockBehavior.Loose, 
                 new SQLitePlatformWin32(),
                 "TestDb");
            var t = mockSQLiteconnection.Object; // fails!!!
        }

当我这样做时会发生另一个例外:

错误:

SetUp : System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
  ----> System.TypeInitializationException : The type initializer for 'SQLite.Net.Platform.Win32.SQLiteApiWin32Internal' threw an exception.
  ----> System.Exception : Failed to load native sqlite library

Codesample:

[SetUp]
public void SetUp()
{
    _aktoerListeDto = MockAktoerListe();
    Mock<SQLiteConnection> mockSQLiteconnection = new Mock<SQLiteConnection>(
        new SQLitePlatformWin32(),
        "TestDb",
        It.IsAny<bool>(),
        It.IsAny<IBlobSerializer>(),
        It.IsAny<IDictionary<string, TableMapping>>(),
        It.IsAny<IDictionary<Type, string>>(),
        It.IsAny<IContractResolver>());
    var t = mockSQLiteconnection.Object;
}

1 个答案:

答案 0 :(得分:1)

SQLiteConnection存在紧密联系。 我认为你应该尝试嘲笑&#34;抽象&#34;而不是&#34;具体&#34; SQLiteConnection课程。检查ISQLiteConnection之类的接口是否存在(或者可以引入),然后继续模拟它。它会使您的系统脱离测试。