Prevent Spring bean re-initialization for each JUnit test - java

I have integration tests based on JUnit that access DB. We also use Liquibase Spring bean to init database.
If I try running multiple tests in parallel each of them tries to initialize DB using Liquibase causing locks and eventually failures since only one instance of Liquibase can modify DB at a time.
The tests are configured as follows:
#RunWith(SpringJUnit4ClassRunner.class)
#Transactional
#WebAppConfiguration
#Sql({"/schema/insert-test-data.sql"})
How can I configure DB initialization (schema and data) that it will be done only once and not for each test?

This is just idea not testet, but if you are not executing scripts in parallel what about using ScriptUtils or ResourceDatabasePopulator iside #Before method with some switch.
#Before
public void init(){
if (wasInitialized)
return;
new ResourceDatabasePopulator(new ClassPathResource("path/to/sql.sql")).execute(dataSource);
wasInitialized = true;
}

Related

#BeforeAll JUnit/spring-boot-test alternative that runs when application context starts

I'm writing a #Repository/#Service integration test that leverages an embedded database. In my test class, I would like to preload my database with some data.
I'm currently using #BeforeEach to load in my sample data, however, this code is run upon each test in my class.
Is there any way that I can load in my test data after Spring application context has loaded, but before any test has been run?
My current approach:
#BeforeEach
public void before() {
repository.save(...); // -> prepopulates repository with sample data
}
#Test
public void testService() {
service.get(...); // -> gathers existing record
}
#Test
public void deleteById() {
service.delete(...); // -> deletes existing record
}
However... with this, I am required to flush out the records after every test. Otherwise any unique constraints can easily be violated.
Rather than using #BeforeEach which is required to run before every test... is it possible to load this in in a #BeforeAll kind of fashion that happens after the spring application context has been loaded?
Is there any way that I can load in my test data after Spring application context has loaded
Basically yes, I think you can do that:
The idea is to load the SQL data when the application context is started or in the process of being started.
For example, spring boot integration with Flyway works this way (the bean of Flyway is created and loaded). So, in theory, you could merely use Flyway with test migrations that will contain all the relevant SQL scripts of test data generation.
How can you do this technically?
Here is one way:
Create a special bean (just like the way it works with Flyway) that would depend on your repository and in post construct save the data:
#Component
public class SqlGenerationBean {
#Autowired
private MyRepository repo;
#PostConstruct
public void init() {
repo.save();
}
}
Another way of doing is to create a listener that will be called upon the application context started and again will call the same repo.save().
In both cases the bean/listener code should not be accessible from production (it's only for tests): so put it somewhere under src/test/java for example
Now once the application context is started you can use a neat trick:
Mark your tests with #Transactional annotation. Spring will wrap the code in an artificial transaction that will be rolled back automatically (even if the test succeeds) so that all the data that you'll modify during the test will be rolled back and basically before each test, you'll have the same state (that is identical to the state of the database when/after the application context starts). Of course, if you use DDL in the test, some databases can't make it a part of transaction but it depends on the database really.
Another interesting point here is that the application context can be cached even between the test cases (created only once), so keep this in mind.
In this case I would just create a constructor for the test class. It will be triggered before everything.
#BeforeEach runs before each tests but after all initialisations .
you can also just use Mockito and mock the result without need to clean and overcomplicate
Just add following snippet to your code. This is just like you can do to detect that Spring application is really started.
#Configuration
public class AppConfig implements ApplicationListener<ApplicationReadyEvent> {
/**
* This is to indicate in the logs when the application has actually started and everything is loaded.
*/
#Override
public void onApplicationEvent(ApplicationReadyEvent event) {
ApplicationContext context = event.getApplicationContext();
Environment env = context.getEnvironment();
// do what you want on application start
}
}
P.S. For database manipulation in test #Sql is the best candidate as was mentioned in comment.

Trouble executing a unit test that should ignore Spring annotations on the unit under test

I'm trying to execute a unit test for a service class that has an #Async("asyncExecutor") annotated method. This is a plain JUnit test class with no Spring runners and no intention of using Spring at all in the unit test. I get the exception,
BeanFactory must be set on AnnotationAsyncExecutionAspect to access qualified executor 'asyncExecutor'
Where asyncExectuor is the name of the bean to be used during normal execution. My configuration class looks like this and I solved that previous error message at runtime by adding the mode = AdviceMode.ASPECTJ portion. This service works at runtime without issue in an Async way.
#Configuration
#EnableAsync(mode = AdviceMode.ASPECTJ)
public class AsyncConfiguration {
#Bean(name = "asyncExecutor")
public Executor asyncExecutor() {
...
}
}
I don't understand why the Spring context is being constructed at all in the unit test. The test class is simply annotated #Test on the methods with no class annotations and no mention of Spring. I was hoping to unit test this service class method as a regular method ignoring the async nature, but the annotation is being processed for some reason.
I'm contributing to a much larger gradle + Spring 4 project that I'm not fully knowledgeable about. Is there anything I should be looking for to see if a Spring context is being created by default for all tests?
As you noticed, Spring context is not loaded, that is the reason of your error. Try to initialize Spring context in your test by adding #RunWith and #ContextConfiguration annotations

Junit Spring avoid to load twice application context datasource

I have this configuration classes:
#ComponentScan(
basePackages = {
"mypackage.controller",
"mypackage.service",
"mypackage.repository"
}
)
#TestPropertySource(locations="classpath:configuration.properties")
#Import({
H2Configuration.class
})
public class TestConfiguration {
}
#Configuration
public class H2Configuration {
#Bean
public DataSource dataSource() throws SQLException {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder
.setType(EmbeddedDatabaseType.H2)
.addScript("h2/create.sql")
.addScript("h2/insert.sql")
.build();
db.getConnection().setAutoCommit(false);
return db;
}
}
And I have this two class tests:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader=AnnotationConfigContextLoader.class, classes = { TestConfiguration.class })
public class FirstRepositoryTest {
#Autowired
MyFirstRepositoryImpl repository;
#Before
public void initTest() {
}
#Test(expected = NullPointerException.class)
public void testNullRecords() {
repository.foo(null, null);
}
}
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader=AnnotationConfigContextLoader.class, classes = { TestConfiguration.class })
public class SecondRepositoryTest {
#Autowired
MySecondRepositoryImpl repository;
#Before
public void initTest() {
}
#Test(expected = NullPointerException.class)
public void testSomethingNullRecords() {
repository.something(null, null);
}
}
If I run junit test once for each class, all goes well.
In clean install phase tests fails because the application context is initialized twice.
For example it try to create the h2 tables twice and do the insert.sql script twice.
What I have to do for initialize the h2 database and so application context only once?
Thanks
I think you could start looking at the Spring documentation about Integration Testing.
It can also be a good practice to use transactional tests for integration tests (#Transactional), which rollback at the end of each test : see Transaction Management.
To avoid the cost of recreating the ApplicationContext for each test class, the cache may be used as explained here : Context Caching.
For integration testing with Embedded Database, you can also find documentation : Testing Data Access Logic with an Embedded Database.
A note from the previous link, matching your use case :
However, if you wish to create an embedded database that is shared
within a test suite, consider using the Spring TestContext Framework
and configuring the embedded database as a bean in the Spring
ApplicationContext as described in Creating an Embedded Database by
Using Spring XML and Creating an Embedded Database Programmatically.
I hope you will find some useful references.
Another good tip I found from Spring Boot documentation from Embedded Database Support :
They say :
If you are using this feature in your tests, you may notice that the
same database is reused by your whole test suite regardless of the
number of application contexts that you use. If you want to make sure
that each context has a separate embedded database, you should set
spring.datasource.generate-unique-name to true.
So to make each EmbeddedDatabase unique, you may try to create them with :
EmbeddedDatabase db = new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
...
.build();
In unit testing you must garantee that every test is repeatible hance context independent. Due to this is not good idea to load the context only once. Is better to reset after the execution. For this you can use #DirtiesContext(classMode = ClassMode.AFTER_CLASS) in your test classes
So you will force your context to restart when the next junit class is launched
So the reason that this is failing is that the database (H2) is resident in memory when you run the tests as part of clean/install. The create/insert scripts have already executed after the first test is run. Any subsequent test execution after this point will result in a re-execution of the same script(s) and the error will occur.
Update your create script with a DROP TABLE IF EXISTS <table name>;. This will ensure that the table is dropped then recreated.
NOTE: I'm not sure why you've specified AnnotationConfigContextLoader explicitly. I think, without that, the runner SpringJUnit4ClassRunner will cache contexts that have not been changed. I don't know specifically if that is the case here though.

Spring's TestNG rollback transaction not working

Following my general question I have a specific issue using spring jdbcTemplate , I want to rollback specific test method after every execution of DAO method below.
Adding #Transactional and #Rollback(true) failed to rollback insert
Also getting connection before/after and rollback it doesn't effect
#Test
#Transactional
#Rollback(true)
public void testInsertUser() {
Assert.assertEquals(userDAO.insertUser(new User(55616103, true, true, false)), true);
}
How should I rollback unit test using TestNG framework? most answers use Junit's #RunWith(SpringJUnit4ClassRunner.class)
I failed auto wiring the jdbcTemplate using TestNG:
#Autowired
private JdbcTemplate jdbcTemplate;
But succeeded using SpringJUnit4ClassRunner with including Configuration class includes jdbcTemplate/DataStource
Do TestNG have option to execute using Spring context?
The solution is to replace the AbstractTestNGSpringContextTests with AbstractTransactionalTestNGSpringContextTests.
reference: Spring + TestNG not transactionally rollback

How to setup/teardown dbunit dataset without using static #BeforeClass

I am trying to use dbunit to test the database of the system. Since several testcases can be tested using same dataset, I want to init the dataset once for all of them. But I also use #AutoWire of spring to init those db connection parameter.
I tried to use #BeforeClass and #AfterClass to setup the db. But turns out the #Autowire happens when class get initiated(not seems not work for auto wire static members).
So wondering is there any other way i can setup/tear down the db dataset before/after all the testcases?
I found one elegant solution:
How to allow instance methods to run as JUnit BeforeClass behavior
This post basically explained a way to change unittest runner to trigger the events.
And for spring, the AbstractTestExecutionListener can be used as well
Just initialize database using the ApplicationListener interface. Please take a look at this question:
How to add a hook to the application context initialization event? It is possible to create all the data in the onApplicationEvent method.
Anyway don't use dbunit, just create all your tests with #Transactional, and #DirtiesContext (DirtiesContext on the class level) using ClassMode=AfterEachTestMethod
So the code would be like this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({ "classpath:testContext.xml" })
#DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class YourTestClassTest {
//...
}
I also use DBUnit for my integration tests and i setup/teardown the data within the #Before and #After annotated methods instead of #BeforeClass/#AfterClass. so each test gets its refreshed test-data.
To use different datasets for each tests or different replacements for a single test you also could call a setup(dataSet) or setup(replacementList) method as first row of your #Test annotated method (than you don't us #Before annotation).

Categories

Resources