开发者

How to make Nhibernate not to persist the changes in object to the database

There is a collection of data in the database on which a integration test is run. For preventing NHibernate persisting o开发者_JS百科bjects modification in the database an EventListener that inherits from DefaultSaveOrUpdateEventListener was implemented.

Then there is a method:

public override void OnSaveOrUpdate(SaveOrUpdateEvent @event)
{
  @event.Session.CancelQuery();
  Trace.TraceWarning("NhibernateSaveUpdateCanceler: Persistence will be ignored.");
}

Unfortunately this does not work as expected. So intended behavior is to catch the moment when changes are written in the database and cancel it somehow though leaving objects as there are so modification on them can be validated.

Thanks.

EDIT

Cannot do this because there are multiple transaction in the tested method so there is contradiction in requirements by persisting changes so that there are available for all transaction from one side and that changes are not persistent in the database from the other.


The SaveOrUpdate event listener is called when session.Save or session.Update is called. When changes are flushed, the FlushEntity event is called for each entity. Implement IFlushEntityEventListener.


re-write your integration test with an Integration test fixture base. in the base class create: a fixture setup that initializes nhibernate and creates a session factory a fixture teardown that closes the session factory a test setup that creates a session and transaction a test teardown that rolls back the transaction and closes the session.

like this

[TestFixture]
public abstract class TestFixtureBase
{
    protected ISessionFactory SessionFactory { get; private set; }
    protected ISession Session { get; private set; }
    protected ITransaction Tx { get; private set; }

    [TestFixtureSetUp]
    public virtual void SetUp()
    {
        var nh = new NHInit();

        nh.Initialize();

        SessionFactory = nh.SessionFactory;
    }

    [TestFixtureTearDown]
    public virtual void TearDown()
    {
        SessionFactory.Close();
    }


    [SetUp]
    public void Test_Set_Up()
    {
        Session = SessionFactory.OpenSession();
        Tx = Session.BeginTransaction();
    }

    [TearDown]
    public void Test_tear_down()
    {
        Tx.Rollback();
        Tx.Dispose();
        Session.Close();
    }
}

then write your test.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜