Ayende在此blog post中有一個很好的示例。他的例子如下所示,我的評論。
由於配置創建起來很昂貴,因此每次測試運行時只創建一次。使用SQLite內存數據庫是因爲這是執行查詢的最快方式。
public class InMemoryDatabaseTest : IDisposable
{
private static Configuration Configuration;
private static ISessionFactory SessionFactory;
protected ISession session;
public InMemoryDatabaseTest(Assembly assemblyContainingMapping)
{
if (Configuration == null)
{
Configuration = new Configuration()
.SetProperty(Environment.ReleaseConnections,"on_close")
.SetProperty(Environment.Dialect, typeof (SQLiteDialect).AssemblyQualifiedName)
.SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
.SetProperty(Environment.ConnectionString, "data source=:memory:")
.SetProperty(Environment.ProxyFactoryFactoryClass, typeof (ProxyFactoryFactory).AssemblyQualifiedName)
.AddAssembly(assemblyContainingMapping);
SessionFactory = Configuration.BuildSessionFactory();
}
session = SessionFactory.OpenSession();
new SchemaExport(Configuration).Execute(true, true, false, true, session.Connection, Console.Out);
}
public void Dispose()
{
session.Dispose();
}
}
當使用這個,每個測試開始創建所需的數據。
public class BlogTestFixture : InMemoryDatabaseTest
{
public BlogTestFixture() : base(typeof(Blog).Assembly)
{
}
[Fact]
public void CanSaveAndLoadBlog()
{
object id;
using (var tx = session.BeginTransaction())
{
id = session.Save(new Blog
{
AllowsComments = true,
CreatedAt = new DateTime(2000,1,1),
Subtitle = "Hello",
Title = "World",
});
tx.Commit();
}
session.Clear();
using (var tx = session.BeginTransaction())
{
var blog = session.Get<Blog>(id);
Assert.Equal(new DateTime(2000, 1, 1), blog.CreatedAt);
Assert.Equal("Hello", blog.Subtitle);
Assert.Equal("World", blog.Title);
Assert.True(blog.AllowsComments);
tx.Commit();
}
}
}
外部資源?那些不再是單元測試你正在嘗試實現,但集成測試。 – 2010-03-17 09:47:08
好的,我知道。讓我們叫它測試然後( - : – cs0815 2010-03-17 10:01:09