UnitTest FluentNhibernate使用PostgreSQLConfiguration [英] UnitTest FluentNhibernate using PostgreSQLConfiguration

查看:224
本文介绍了UnitTest FluentNhibernate使用PostgreSQLConfiguration的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设置我们的新体系结构时,我遵循了使用 NHibernate MsSql2008 配置的指南。



我们没有使用 MsSql2008 ,而是使用 Postgresql 。这一切的配置工作很好,它保存到数据库等。

我试图写一个单元测试来测试 UoW

code>但我无法得到 InMemory 配置才能正常工作。



使用下面的Provider:

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ { b $ b {
var databaseDriver = SQLiteConfiguration.Standard.InMemory()。ShowSql();
返回CreateCoreDatabaseConfiguration(databaseDriver);

$ b $ public static void InitialiseDatabase(Configuration configuration,ISession session)
{
新建SchemaExport(配置).Execute(true,true,false,session.Connection ,Console.Out);




$ b我的标准(Non UnitTest)配置如下所示:

  public abstract class NHibernateConfigurationProvider:INHibernateConfigurationProvider 
{
public abstract Configuration GetDatabaseConfiguration();

配置CreateCoreDatabaseConfiguration(
IPersistenceConfigurer databaseDriver,
Action< Configuration> databaseBuilder = null)
{
var fluentConfiguration =
流利的配置()
.Database(databaseDriver)
.Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf< Organization>(new DefaultMappingConfiguration())
//.Conventions.AddFromAssemblyOf< ; IdGenerationConvention>()
.UseOverridesFromAssemblyOf< OrganisationMappingOverride>()));

if(databaseBuilder!= null)
{
fluentConfiguration.ExposeConfiguration(databaseBuilder);
}

return fluentConfiguration.BuildConfiguration();



$ b public class PostgreSQLServerNHibernateConfigurationProvider:NHibernateConfigurationProvider
{
private static readonly string NpgsqlConnectionString = ConfigurationManager.ConnectionStrings [ProdDBConnection] .ConnectionString;

public override配置GetDatabaseConfiguration()
{
返回CreateCoreDatabaseConfiguration(
PostgreSQLConfiguration.Standard.ConnectionString(NpgsqlConnectionString)。
方言(NHibernate.Dialect。 PostgreSQL82Dialect).ShowSql(),
BuildDatabase);
}

....... //其他方法等
}

如何使用 PostgresqlConfiguration 而不是<$ c来测试 InMemoryConfigurationProvider $ C> SqlLiteCOnfiguration PostgresqlConfiguration 没有 InMemory 选项。



我实现一个配置,创建另一个数据库,只是把它放在拆解?或者是否有另一种方法呢?

解决方案

使用sqlite工作得很好,虽然它与SQL-服务器,我们使用他们是如此轻微的测试无关紧要。
这就是说,我们如何设置测试:
所有我们想要从db写入/读取的测试用例扩展了 SqLiteTestBase 类。这样他们都可以访问由basesetup方法创建的会话,并可以根据需要设置daos /存储库。
使用这种方法,我们也总是为每个测试用例获得一个新的数据库。

更新:
在尝试了更多一点之后,实际上发现你必须稍微修改一下才能使用 InMemory (我们之前使用的是由磁盘上的文件支持的sqlite)。所以更新的(完整)设置如下所示:

  private Configuration _savedConfig; 
$ b $ SetUp
public void BaseSetup()
{

FluentConfiguration配置=
流利的.Configure()
$
.ExposeConfiguration(
x => x.SetInterceptor(new MultiTenancyInterceptor(ff)))
.Mappings(m = > m.FluentMappings.AddFromAssemblyOf< IRepository>())
.Mappings(m => m.FluentMappings.ExportTo(c:\\temp\\\pping))
.ExposeConfiguration(x => _savedConfig = x)//保存创建模式时使用的nhibernate配置,以便能够使用相同的连接
.ExposeConfiguration(x => ConfigureEnvers(x))
.ExposeConfiguration(x => ConfigureListeners(x));

ISessionFactory sessionFactory;
尝试
{
sessionFactory = configuration.BuildSessionFactory();
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
throw;
}
_session = sessionFactory.OpenSession();

BuildSchema(_savedConfig,_session);

$ b私有无效BuildSchema(配置配置,ISession会话)
{
新建SchemaExport(config)
.Execute(false,true,false, session.Connection,null);

$ / code $


为什么你必须跳过所有这些箍以便使用内存版本的Sqlite是由于数据库连接到连接。你必须使用相同的连接来创建数据库来填充模式,因此我们必须保存 Configuration 对象,以便我们可以在创建后的时候导出模式连接。

看到这个博客的一些更多的细节: http://www.tigraine.at/2009/05/29/fluent-nhibernate-gotchas-when-testing- with-in-in-memory-database /



注意:这只显示db的设置。我们有一些代码,也用标准值(用户,客户,masterdata等)填充数据库,但为了简洁起见,我省略了这些代码。

When setting up our new architecture I followed a guide which used NHibernate with MsSql2008 configuration.

We are not using MsSql2008, instead using Postgresql. The configuration for this all works great and it saves to the database etc.

I am trying to write a unit test to test the UoW but I can't get the InMemory configuration to work.

The guide that I followed used this following Provider:

public class InMemoryNHibernateConfigurationProvider : NHibernateConfigurationProvider
{
    public override Configuration GetDatabaseConfiguration()
    {
        var databaseDriver = SQLiteConfiguration.Standard.InMemory().ShowSql();
        return CreateCoreDatabaseConfiguration(databaseDriver);
    }

    public static void InitialiseDatabase(Configuration configuration, ISession session)
    {
        new SchemaExport(configuration).Execute(true, true, false, session.Connection, Console.Out);
    }
}

My standard (Non UnitTest) configuration looks like this:

public abstract class NHibernateConfigurationProvider : INHibernateConfigurationProvider
{
    public abstract Configuration GetDatabaseConfiguration();

    public Configuration CreateCoreDatabaseConfiguration(
        IPersistenceConfigurer databaseDriver,
        Action<Configuration> databaseBuilder = null)
    {
        var fluentConfiguration =
            Fluently.Configure()
            .Database(databaseDriver)                
            .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Organisation>(new DefaultMappingConfiguration())
                //.Conventions.AddFromAssemblyOf<IdGenerationConvention>()
                 .UseOverridesFromAssemblyOf<OrganisationMappingOverride>()));

        if (databaseBuilder != null)
        {
            fluentConfiguration.ExposeConfiguration(databaseBuilder);
        }

        return fluentConfiguration.BuildConfiguration();
    }
}


public class PostgreSQLServerNHibernateConfigurationProvider : NHibernateConfigurationProvider
{
    private static readonly string NpgsqlConnectionString = ConfigurationManager.ConnectionStrings["ProdDBConnection"].ConnectionString;

    public override Configuration GetDatabaseConfiguration()
    {
        return CreateCoreDatabaseConfiguration(
            PostgreSQLConfiguration.Standard.ConnectionString(NpgsqlConnectionString).
                Dialect("NHibernate.Dialect.PostgreSQL82Dialect").ShowSql(),
            BuildDatabase);
    }

    ....... // Other Methods etc
}

How do I write a InMemoryConfigurationProvider that tests using PostgresqlConfiguration instead of SqlLiteCOnfiguration. PostgresqlConfiguration does not have an InMemory option.

Do I implement a configuration that creates another database and just drop it on teardown? Or is there perhaps another way of doing it?

解决方案

Using sqlite works really well and although it does have some differences to SQL-server which we use they are so minor it doesn't matter for testing purposes. With that said, this is how we setup the tests: All test-cases where we want to write/read from db extend the SqLiteTestBaseclass. That way they all get access to a session created by the basesetup method, and can setup the daos / repositories as needed. Using this approach we also always get a fresh new db for each test-case.

Update: After trying this out a bit more I actually found that you have to modify it a bit to use InMemory (we had previously used sqlite backed by a file on disk instead). So the updated (complete) setup looks like this:

private Configuration _savedConfig;

[SetUp]
public void BaseSetup()
{

    FluentConfiguration configuration =
                    Fluently.Configure()

                        .Database(SQLiteConfiguration.Standard
                                            .InMemory)
                        .ExposeConfiguration(
                            x => x.SetInterceptor(new MultiTenancyInterceptor(ff)))
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<IRepository>())
                        .Mappings(m => m.FluentMappings.ExportTo("c:\\temp\\mapping"))
                        .ExposeConfiguration(x => _savedConfig = x) //save the nhibernate configuration for use when creating the schema, in order to be able to use the same connection
                        .ExposeConfiguration(x => ConfigureEnvers(x))
                        .ExposeConfiguration(x => ConfigureListeners(x));

    ISessionFactory sessionFactory;
    try
    {
        sessionFactory = configuration.BuildSessionFactory();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.StackTrace);
        throw;
    }
    _session = sessionFactory.OpenSession();

    BuildSchema(_savedConfig, _session);
}

private void BuildSchema(Configuration config, ISession session)
{
    new SchemaExport(config)
     .Execute(false, true, false, session.Connection, null);
}

The reason why you have to jump through all these hoops in order to use the in-memory version of Sqlite is due to the db being tied to the connection. You have to use the same connection that creates the db to populate the schema, thus we have to save the Configuration object so that we can export the schema later when we've created the connection.

See this blogpost for some more details: http://www.tigraine.at/2009/05/29/fluent-nhibernate-gotchas-when-testing-with-an-in-memory-database/

N.B: This only shows the setup of the db. We have some code which also populates the db with standard values (users, customers, masterdata etc) but I've omitted that for brevity.

这篇关于UnitTest FluentNhibernate使用PostgreSQLConfiguration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆