0

I am using Apache Deltaspike with OpenWebBeans for CDI in a Java SE project. I've used Spring Data JPA in a Java EE project and it was easy enough to setup unit tests that didn't commit data to the database by adding the @Transactional annotation above the class or test methods. However, I haven't been able to find an equivalent technique with Deltaspike.

Apart from manually rolling back data after each test or by deleting and re-creating the database each time a test is run, is there any way to specify that each unit test should rollback data changes after completing?

My unit tests look somewhat like the following:

@RunWith(CdiTestRunner.class)
@Transactional // has no effect
public class FooUnitTest {
    @Inject
    private FooRepository fooRepository;

    @Test
    @Transactional // no effect either
    public void testFoo() {
        Foo foo = new Foo();
        fooRepository.save(foo); // foo is persisted even outside the test
    }
}

@Repository
public interface FooRepository extends EntityRepository<Foo, Integer> { }
Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
David Yee
  • 3,515
  • 25
  • 45
  • The docs note : "return true to trigger #rollback for the current transaction(s), false otherwise" https://deltaspike.apache.org/javadoc/1.4.0/org/apache/deltaspike/jpa/api/transaction/Transactional.html – Alan Hay Feb 08 '16 at 17:09
  • @AlanHay Yes, I've given that a try already too. – David Yee Feb 08 '16 at 17:11
  • If you roll it back, you don't know if a commit would have worked. But basically use @Transactional(readOnly=true) and if you like to annotate your test-class, you have to configure: deltaspike.testcontrol.use_test_class_as_cdi_bean=true (in META-INF/apache-deltaspike.properties) If you like to reset the data but not the tables, you need the statement which works for your db (like truncate schema). – Dar Whi Feb 12 '16 at 22:37
  • You could also have a look at: org.apache.deltaspike.testcontrol.spi.junit.TestStatementDecoratorFactory there is an implementation called TransactionStatementDecoratorFactory which does a rollback. – Dar Whi Feb 12 '16 at 23:13
  • I have a question to your code. Now I am trying to run units for delta spike data module - I want to test repository. As CDI implementation I am using JBoss Weld. However, my junits do not work because they cannot inject repository. Did you have similar problem? How did you handle with it? Thanks – Adam May 20 '18 at 19:02

0 Answers0