Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine many Spring test annotations in a single annotation?

I am using Spring Boot's convenient 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

I found it quite ugly to copy/paste this whole block on each test class, so I have created my own @MyIntegrationTest annotation

@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 the @RunWith(SpringJUnit4ClassRunner.class) in my new annotation, then JUnit will run with its default runner - which is not desirable. So for now I have to use two annotations.

@RunWith(SpringJUnit4ClassRunner.class)
@MyIntegrationTest

I guess it is fine for now, but is there a way to combine these annotations, so I would be able to use a single annotation?

like image 988
Guillaume Avatar asked Jun 28 '15 09:06

Guillaume


People also ask

Can we have multiple beans of a same type in a class?

2. Using Java Configuration. This is the simplest and easiest way to create multiple beans of the same class using annotations. In this approach, we'll use a Java-based configuration class to configure multiple beans of the same class.

Can you apply more than one annotation on any method?

You can repeat an annotation anywhere that you would use a standard annotation.

What is SpringBootTest annotation?

Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication .


1 Answers

Meta-annotations are not the only way of code reuse. We use inheritance instead:

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

public class FooTest extends IntegrationTest {

}

public class BarTest extends IntegrationTest {

}

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

like image 81
meriton Avatar answered Oct 03 '22 18:10

meriton