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?
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.
You can repeat an annotation anywhere that you would use a standard 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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With