我正在尝试使用内存中的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
最初我使用自己的代码进行连接/会话管理,但已转移到转换为C#的this blog post中的代码,并对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");
}
我在阅读this
后添加了on_close我的测试代码如下:
[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);
}
}
}
我在这里忽略了什么?
更新:我创建了一个连接到SQLite文件数据库的类的副本,它运行正常。所以它必须与关闭连接有关。
答案 0 :(得分:3)
如果您将测试方法更改为以下内容,它是否有效?
[Test]
public void CanGetStudentById()
{
using (var scope = new SQLiteDatabaseScope<StudentMapping>())
{
using (ISession sess = scope.OpenSession())
{
// Arrange
sess.Save(new Student() { Name = "Text1", DoB = DateTime.Now });
// Act
var student = sess.Get<Student>(1);
// Assert
Assert.IsNotNull(student);
Assert.AreEqual("Text1", student.Name);
}
}
}
我猜测你的StudentRepository正在打开它自己的会话,因此不会看到该表。