Eugeniu Torica
Eugeniu Torica

Reputation: 7574

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 objects 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.

Upvotes: 0

Views: 388

Answers (2)

Fran
Fran

Reputation: 6520

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.

Upvotes: 1

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

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.

Upvotes: 2

Related Questions