我正在尝试使用内存中的 SQLite 数据库来测试 NHibernate 提供的数据层。
我读过很多关于如何进行此设置的博客和文章,但我现在很困惑为什么它不起作用。
问题 - 当我运行单元测试时,我收到错误“没有这样的表:学生”。我读过的文章表明这是因为架构未生成,或者我的 SchemaExport 和查询之间的连接正在关闭。我检查了我能想到的所有地方,但看不出这两种情况是如何发生的。
我的测试输出日志如下所示:
OPEN CONNECTION
drop table if exists "Student"
drop table if exists "Tutor"
create table "Student" (
ID integer,
Name TEXT,
DoB DATETIME,
TutorId INTEGER,
primary key (ID)
)
create table "Tutor" (
ID integer,
Name TEXT,
primary key (ID)
)
NHibernate: INSERT INTO "Student" (Name, DoB, TutorId) VALUES (@p0, @p1, @p2); select last_insert_rowid();@p0 = 'Text1', @p1 = 01/12/2010 14:55:05, @p2 = NULL
14:55:05,750 ERROR [TestRunnerThread] AbstractBatcher [(null)]- Could not execute query: INSERT INTO "Student" (Name, DoB, TutorId) VALUES (@p0, @p1, @p2); select last_insert_rowid()
System.Data.SQLite.SQLiteException (0x80004005): SQLite error
no such table: Student
at System.Data.SQLite.SQLite3.Prepare(String strSql, SQLiteStatement previous, String& strRemain)
at System.Data.SQLite.SQLiteCommand.BuildNextCommand()
at System.Data.SQLite.SQLiteCommand.GetStatement(Int32 index)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
14:55:05,781 ERROR [TestRunnerThread] ADOExceptionReporter [(null)]- SQLite error
no such table: Student
DISPOSE
CLOSING CONNECTION
最初我使用自己的代码进行连接/会话管理,但已转移到中的代码这篇博文 http://jasondentler.com/blog/2009/08/nhibernate-unit-testing-with-sqlite-in-memory-db/翻译为 C#,并对 DBConfig 方法进行了一些更改,并使用一些调试语句来显示连接状态。
private FluentNHibernate.Cfg.Db.IPersistenceConfigurer GetDBConfig()
{
return SQLiteConfiguration.Standard
.ConnectionString((ConnectionStringBuilder cs) => cs.Is(CONNECTION_STRING))
.ProxyFactoryFactory("NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu")
.Raw("connection.release_mode", "on_close");
}
我读完后添加了 on_closethis http://www.codethinked.com/nhibernate-20-sqlite-and-in-memory-databases
我的测试代码如下所示:
[Test]
public void CanGetStudentById()
{
using (var scope = new SQLiteDatabaseScope<StudentMapping>())
{
using (ISession sess = scope.OpenSession())
{
// Arrange
var repo = new StudentRepository();
repo.Save(new Student() { Name = "Text1", DoB = DateTime.Now });
// Act
var student = repo.GetById(1);
// Assert
Assert.IsNotNull(student);
Assert.AreEqual("Text1", student.Name);
}
}
}
我在这里忽略了什么?
Update:我创建了一个连接到 SQLite 文件数据库的类的副本,它工作得很好。所以这一定与连接被关闭有关。