测试 "one-to-many" 关系时获取重复项?

Getting duplicates when testing "one-to-many" relationship?

我 运行 遇到了一些测试 Fluent NHibernate 持久性的问题。我不确定这是否只是我的理解不足或对测试的不当期望。如果是这样,有人对如何最好地为 DAL 的这一部分设置单元测试有任何建议吗?

我有一对 类 ClientFacility 一对多关系:

One: Client can have Many Facility

使用这个 FluentNHibernate 的映射结构,我希望它们看起来应该是这样的:

public class ClientMapping : DataMapping<Client>
{
    public ClientMapping()
    {
        HasMany(client => client.Facilities)
            .Inverse()
            .Cascade
            .All();
    }
}

public class FacilityMapping : DataMapping<Facility>
{
    public FacilityMapping()
    {
        References(fac => fac.Owner);
    }
}

我听从了 FNH 关于创建测试的建议,如下所示,但是当 运行 它时 - 我得到一个 Client table 和一个 Facility [=42] =] 有两个不同的 ID,即使我传递的是一个对象。

    [Test]
    public void CanCorrectlyCreateFacilityTable()
    {
        _client = new Client {Name = "Preston"};

        new PersistenceSpecification<Facility>(session, new DataEqualityComparer())
            .CheckProperty(f => f.Id, 1)
            .CheckProperty(f => f.Name, _facility1.Name)
            .CheckReference(f => f.Owner, _client)
            .VerifyTheMappings();

        new PersistenceSpecification<Facility>(session, new DataEqualityComparer())
            .CheckProperty(f => f.Id, 2)
            .CheckProperty(f => f.Name, _facility2.Name)
            .CheckReference(f => f.Owner, _client)
            .VerifyTheMappings();

    }

最接近的 q/a 我发现的是下面的那些,但即使 运行 首先进行 Client 测试,我似乎也得到了相同的结果(可能是因为数据库状态会自行重置对于每个测试):

Hibernate - one to Many relationship

原来我的预期是错误的。持久性规范测试只是测试数据到达数据库的位置 - 因此,它会在每次 运行 时发送新项目。

为了测试映射是否正确地级联数据,我需要编写如下测试:

    [Test]
    public void CanSaveAndLoadFacilityMapping()
    {
        object id;
        object id2;

        using (var trans = _session.BeginTransaction())
        {
            id = _session.Save(_facility1);
            id2 = _session.Save(_facility2);

            trans.Commit();
        }

        _session.Clear();

        using (var trans = _session.BeginTransaction())
        {
            var facility = _session.Get<Facility>(id);
            var facility2 = _session.Get<Facility>(id2);

            Assert.AreEqual(facility.Name, _facility1.Name);
            Assert.AreEqual(facility.Owner.Name, _client.Name);
            Assert.AreEqual(facility2.Owner.Name, _client.Name);
            Assert.AreEqual(facility.Owner.Id, facility2.Owner.Id);

            trans.Dispose();
        }
    }