c#中使用Moq和SQLiteConnection

本文关键字:SQLiteConnection Moq | 更新日期: 2023-09-27 18:07:33

我试图了解如何使用SQLiteConnection Moq。问题是,由于我对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;
}

c#中使用Moq和SQLiteConnection

SQLiteConnection紧密耦合。我认为你应该试着嘲笑一个"抽象"而不是"具体"的SQLiteConnection类。检查像ISQLiteConnection这样的接口是否存在(或可以引入),然后继续模拟它。它会解耦被测系统。