Files
ebean/ebean-test/src/test/java/org/tests/transaction/TestTransactionCallback.java
T
Rob Bygrave 4d34c9e868 #2424 Change error for transaction register(Callback) when no active transaction from PersistenceException to NullPointerException
Ah ok, so in being more strict on null for currentTransaction() that shows up the code that registers transaction callbacks as checking for null and throwing PersistenceException. This is inconsistent with LOTS of other methods that use currentTransaction() and would result in NPE.

The concept here is that PersistenceException for this case isn't better than NPE and NPE is actually more consistence wrt using currentTransaction().
2021-10-21 12:02:42 +13:00

106 lines
2.5 KiB
Java

package org.tests.transaction;
import io.ebean.BaseTestCase;
import io.ebean.DB;
import io.ebean.Transaction;
import io.ebean.TransactionCallbackAdapter;
import org.junit.jupiter.api.Test;
import javax.persistence.PersistenceException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class TestTransactionCallback extends BaseTestCase {
int countPreCommit;
int countPostCommit;
int countPreRollback;
int countPostRollback;
@Test
public void test_commitAndRollback() {
try (Transaction txn = DB.beginTransaction()) {
DB.register(new MyCallback());
txn.connection(); // Ebean assumes writes have occurred
txn.commit();
}
assertEquals(1, countPreCommit);
assertEquals(1, countPostCommit);
assertEquals(0, countPreRollback);
assertEquals(0, countPostRollback);
DB.beginTransaction();
try {
DB.register(new MyCallback());
} finally {
DB.rollbackTransaction();
}
assertEquals(1, countPreCommit);
assertEquals(1, countPostCommit);
assertEquals(1, countPreRollback);
assertEquals(1, countPostRollback);
}
@Test
public void test_commit_whenNoDbWrite() {
try (Transaction txn = DB.beginTransaction()) {
DB.register(new MyCallback());
txn.commit();
}
assertEquals(1, countPreCommit);
assertEquals(1, countPostCommit);
assertEquals(0, countPreRollback);
assertEquals(0, countPostRollback);
}
@Test
public void test_rollback_whenNoDbWrite() {
try (Transaction txn = DB.beginTransaction()) {
DB.register(new MyCallback());
txn.rollback();
}
assertEquals(0, countPreCommit);
assertEquals(0, countPostCommit);
assertEquals(1, countPreRollback);
assertEquals(1, countPostRollback);
}
@Test
public void test_noActiveTransaction() {
assertThrows(NullPointerException.class, () -> DB.register(new MyCallback()));
}
@Test
public void test_noActiveTransaction_withDatabase() {
assertThrows(NullPointerException.class, () -> DB.getDefault().register(new MyCallback()));
}
class MyCallback extends TransactionCallbackAdapter {
@Override
public void preCommit() {
countPreCommit++;
}
@Override
public void postCommit() {
countPostCommit++;
}
@Override
public void preRollback() {
countPreRollback++;
}
@Override
public void postRollback() {
countPostRollback++;
}
}
}