用db文件进行Sqlite单元测试

本文关键字:Sqlite 单元测试 db 文件 | 更新日期: 2023-09-27 18:03:23

我正在浏览一些来自DDD项目的开放源代码示例的代码。. Net和遇到了一个"有趣的"SQLite基础测试夹具(完整的代码在链接中)。

而我通常使用连接字符串SQLite:

"Data Source=:memory:;Version=3;New=True;Pooling=True;Max Pool Size=1")

这个作者正在使用一个DbFile(他设置/删除每个测试):

"Data Source={0};Version=3;New=True;", DatabaseFile)
这样做的好处是什么?

欢呼,
Berryl

<标题>编辑

我怀疑可能是一个优势的原因是,该类中的代码平衡(如下)表明作者既不简单也不幼稚。这种优势不太可能是性能。我猜它可能会使SQLite在测试运行中更可靠,但这就是为什么我问:——)

  protected IDisposable Scope(bool transactional)
  {
     return new ScopeImpl(SessionFactory, transactional);
  }
  protected IDisposable Scope(bool transactional, string description)
  {
     Console.WriteLine(description);
     return Scope(transactional);
  }
  private class ScopeImpl : IDisposable
  {
     private readonly ISessionFactory _sessionFactory;
     public ScopeImpl(ISessionFactory sessionFactory, bool transactional)
     {
        _sessionFactory = sessionFactory;
        ISession session = _sessionFactory.OpenSession();
        if (transactional)
        {
           session.BeginTransaction();
        }
        CurrentSessionContext.Bind(session);
     }
     public void Dispose()
     {
        ISession session = CurrentSessionContext.Unbind(_sessionFactory);
        if (!IsInExceptionContext())
        {               
           if (session.Transaction != null)
           {
              session.Transaction.Commit();
              session.Transaction.Dispose();
           }               
        }
        session.Close();            
     }
     /// <summary>
     /// Checks if current code is running in finally block ater throwing exception.
     /// </summary>         
     private static Boolean IsInExceptionContext()
     {
        return Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0;
     }

用db文件进行Sqlite单元测试

我认为基于文件的SqLite的优点是你可以在同一个文件上打开不同的会话,这样就可以在随后的一个会话中访问插入到前一个会话中的数据(例如断言),而内存中的数据库在单个会话中工作,至少在FluentNHibernate的配置方式中是这样的。另外,如果只在测试设置时删除该文件,那么在最后一次测试后磁盘上仍然有该文件,可以查看它。