tags:

views:

73

answers:

7

How can i force Nhibernate transaction to fail(from the calling code) so i can make sure that the failing behavior is working properly?

I can't modify the source code i just need to make it fail!

example :

public void DoSomething(/*Some parameters*/){
using (var tx = _session.BeginTransaction())
{
    try
    {
        //Do something
        tx.Commit();
    }
    catch (Exception)
    {
        if (tx != null) tx.Rollback();
            throw;
    }
} }
A: 

One idea would be while you're debugging stop at the line immediately before the query execution will be begin and turn off the database then let the code run. However I assume there is a better and more programmatic way to test this.

Chris Marisic
+3  A: 

Throw an exception.

epitka
example maybe ?
Yassir
throw new Exception();
epitka
are you serious ? please read the question ...
Yassir
oh, sorry, I did not see the italics code, my bad. Can you mock the call to it, and then set it to throw execption on call to the method. Take a look at MOQ, very easy to start using.
epitka
A: 

Set some global variable (I know people had global variables but this is a good use) that the transaction internal code reads and if it sees the variable set throw an exception.

Joshua
+2  A: 

Throw an exception:

using(var sess = sf.OpenSession())
    using(var tx = sess.BeginTransaction())
        throw new Exception();

Close the connection:

using(var sess = sf.OpenSession())
    using(var tx = sess.BeginTransaction())
        sess.Connection.Close();

Rollback the transaction:

using(var sess = sf.OpenSession())
    using(var tx = sess.BeginTransaction())
        tx.Rollback();
Justice
+1  A: 

If you have to have the exception occur within the tx.Commit(), then maybe insert/update a record with invalid data (e.g. a string that's too long for the db column).

Kevin Pang
A: 

You can write a unit test to verify the expected behaviour of your code.

Paco
A: 

One way to do it is:

[Test]
public void VerifyExceptionIsThrown()
{
    Assert.Throws<NHibernate.HibernateException>(
       () =>
       {
             using (var tx = _session.BeginTransaction())
             {
                 _session.Update(new Entity());
                 tx.Commit();
             }
       });
}

An attempt to update a transient entity will throw an exeption.

Alternatively if you use the NHibernateValidator you can explicitly fail a validation you have set, say you entity's Name property should no more than 10 characters long. If you populate your entity's Name property with a string longer than 10 characters and you try to Save it, the tx.Commit() will throw you an exception.

tolism7