2

我有一个 NHibernate 拦截器,它覆盖该Instanciate方法,并执行以下操作:

  • 如果要实例化的类继承了某个基类,则返回一个 CastleDynamicProxy
  • 否则只是实例化类

虽然这听起来很简单(并且已经有效),但如果我可以通过单元测试证明它的功能,我仍然会感觉更好。

这是拦截器代码:

    public override object Instantiate(string entityTypeName, EntityMode entityMode, object id)
    {
        // Type resolution across Assembly borders
        Type type = TypeFinder.FindType(entityTypeName);

        if (type == null)
        {
            throw new Exception(string.Format("",entityTypeName));
        }

        bool isViewModel = (typeof(ViewModelBase).IsAssignableFrom(type));

        if (entityMode == EntityMode.Poco && isViewModel)
        {
            var instance = ProxyFactory.CreateProxy(type);
            SessionFactory.GetClassMetadata(entityTypeName).SetIdentifier(instance, id, entityMode);
            return instance;
        }
        return base.Instantiate(entityTypeName, entityMode, id);
    }

我可以成功测试我的代理生成代码,但base.Instantiate总是返回 null。这是我的测试代码(如您所见,我什至添加了一个真实的数据库,以防拦截器需要一个有效的会话):

    private FluentConfiguration PrepareDataBase()
    {
        string connectionString = @"Data Source=test.sdf;";
        SqlCeEngine en = new SqlCeEngine(connectionString);
        en.CreateDatabase();

        FluentConfiguration fc = Fluently.Configure().Database(MsSqlCeConfiguration.Standard
                                                              .ConnectionString(c => c.Is(connectionString))
                                                              .ShowSql())
                                   .Mappings(x => x.FluentMappings.AddFromAssemblyOf<ViewModel>());

        new SchemaExport(fc.BuildConfiguration()).Create(true, true);
        return fc;
    }

    [TestMethod]  
    [DeploymentItem("System.Data.SqlServerCe.dll")]
    public void Test_Instantiate_WithNonViewModelBasedPoco_ReturnsInstance()
    {
        TypeFinder.RegisterAssembly(typeof(OtherPoco).Assembly);
        FluentConfiguration fc = PrepareDataBase();

        NhChangeNotificationInterceptor interceptor = new NhChangeNotificationInterceptor(); 
        ISession session = fc.BuildSessionFactory().OpenSession(interceptor);

        string instanceType = typeof(OtherPoco).FullName;
        object instance = interceptor.Instantiate(instanceType, EntityMode.Poco, null);

        Assert.AreEqual(typeof(OtherPoco).FullName, instance.GetType().FullName);
        Assert.IsFalse(typeof(ViewModelBase).IsAssignableFrom(instance.GetType()));
    }

我认为这可能是空标识符的问题,所以我保存了一条记录并尝试像这样添加它的 Id:

        NhChangeNotificationInterceptor interceptor = new NhChangeNotificationInterceptor(); 
        ISession session = fc.BuildSessionFactory().OpenSession(interceptor);
        using (ITransaction trx = session.BeginTransaction())
        {
            session.Save(new OtherPoco() { Id = 1 });
            session.Flush();
        }
        string instanceType = typeof(OtherPoco).FullName;
        object instance = interceptor.Instantiate(instanceType, EntityMode.Poco, 1);

不过,什么都改变不了。知道如何测试base.Instantiate吗?

4

1 回答 1

2

我不会尝试为此编写单元测试。拦截器与 NH/数据库紧密耦合——最好为此编写集成测试。

不要试图测试你的代码行。相反,测试您的功能。您已经说明了您的拦截器应该做什么(“如果要实例化的类继承某个基类,则返回 CastleDynamicProxy 否则只需实例化该类”)。改为测试这个!如果您以后想使用拦截器以外的其他技术来获得相同的结果,则不应强迫您修改测试。

因此,不要直接从您的测试中调用interceptor.Instantiate,而是进行一些集成测试,以验证它在从数据库中获取数据时是否做了它应该做的事情。

于 2013-02-25T14:55:58.667 回答