How to combine many Spring test annotations in one annotation?

I use Spring Downloadable handy annotations on my test classes, for integration tests.

@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Config.class) @IntegrationTest @Sql({"classpath:rollback.sql", "classpath:create-tables.sql"}) @Transactional 

It was pretty ugly for me to copy / paste this whole block to each test class, so I created my own annotation @MyIntegrationTest

 @SpringApplicationConfiguration(classes = Config.class) @IntegrationTest @Sql({"classpath:database-scripts/rollback.sql", "classpath:database-scripts/create-tables.sql", "classpath:database-scripts/insert-test-data.sql"}) @Transactional @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(value = RetentionPolicy.RUNTIME) @interface MyIntegrationTest { } 

However, if I add @RunWith(SpringJUnit4ClassRunner.class) to my new annotation, then JUnit will work with its default running one, which is undesirable. So for now, I have to use two annotations.

 @RunWith(SpringJUnit4ClassRunner.class) @MyIntegrationTest 

I assume this is normal now, but is there a way to combine these annotations, so I could use one annotation?

+6
source share
2 answers

Meta annotations are not the only way to reuse code. Instead, we use inheritance:

 @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Config.class) @IntegrationTest @Sql({"classpath:rollback.sql", "classpath:create-tables.sql"}) @Transactional abstract class IntegrationTest { } class FooTest extends IntegrationTest { } class BarTest extends IntegrationTest { } 

Unlike meta annotations, the inheritance of annotations from base classes is understood by both Spring and JUnit.

+4
source

Ok, so I found some old discussions about this on JUnit GitHub:

This is a kind of compromise between readability and dryness.

Enabling some meta annotations can also slow down tools like the IDE.

It seems to me that this is not so soon, because at the moment I will have to leave my two annotations.

0
source

Source: https://habr.com/ru/post/989883/


All Articles