Connections are not closed and piling up when running #SpringBootTest classes - spring

We have Spring Boot integration tests, and keep writing new ones regularly.
I noticed database connections have been piling up: the more tests I run, the higher the connection peak to my PostgreSQL instance.
It reached a point where there are more than 300 connections requested by Spring Boot when running all tests, and it started failing the build (our max_connection is set to 300).
After some research, it came to my understanding that connections are not being released after tests have been run, because of Spring Boot test: if context is not explicitly destroyed, connections are not closed.
I find it quite weird, but tried using #DirtiesContext to prove a point, on all of our test classes, it indeed fixed the issue in a sense that it avoided peaks (no more than 30 connections at once, not piling up to 300 like before) but since this annotation forces context recreation before each test class, the build got much slower and I find it not very satisfactory to need to recreate a Spring context every time just to make sure connections are closed properly.
Data source is a HikariDataSource, configured using a configuration class.
Another workaround I found is to change maximum pool size for Hikari. I set it to something lower than the default value of 10 (I'm not sure it's useful to reserve 10 connections for each test class).
This change effectively lowers the total number of connections when I run all tests but they are still piling up (only lower!)
I think I'm missing something, how can I ensure that connections are closed after each test class? There has to be a better way than #DirtiesContext, I just can't find it. Thanks for your help.

It turns out that context was recreated almost with every test class because I was extensively using #MockBean annotation in my tests. Since it affects Spring context, each #MockBean/No MockBean combination in different test classes counts as a different context, i.e.:
Test class 1: bean MyService is a MockBean, MyOtherService is not
Test class 2: bean MyService is a MockBean, MyOtherService is also a MockBean
Test class 3: none of these two beans is a MockBean
In such case, a new Spring context will created for each class because the bean configuration is different, resulting in an increasing number of connections to the datasource.
To (partially) solve this, I looked for patterns in the beans combinations of my test classes and created a new class I called TestMockBeans.
Its sole purpose is to declare as many MockBeans and/or SpyBeans as possible to re-use in similar test configurations. I extend corresponding test classes with TestMockBeans, and then, because they share this similar setup, Spring identifies their contexts as similar and does not recreate a new one for every test class.
As you can guess, not all of my tests throughout the Spring boot app share the same need for Mockbeans (or absence of Mockbeans) so it's only a partial solution, but I hope it will help someone experiencing the same issue to mitigate it.

Related

Spring Boot Scheduler

I have used a Spring Boot Scheduler with #Scheduled annotation along with fixedRateString of 1 sec. This scheduler intermittently stops working for approx 2 min and then starts working automatically. What can be the possible reasons for this behavior and do we have any resolution to this?
Below is the code snippet for the scheduler.
1st) Please read SO guidelines
DO NOT post images of code, data, error messages, etc. - copy or type
the text into the question. Please reserve the use of images for
diagrams or demonstrating rendering bugs, things that are impossible
to describe accurately via text.
2nd) To your problem
You use a xml spring based configuration where you have configured your sheduler. Then you also use the annotation #Scheduled. You should not mix those 2 different types of configuring beans.
Also you use some type of thread synchronization into this method. Probably some thread is stuck outside of the method because of the lock and this messes the functionality that you want.
Clean either the xml configuration or the annotation for scheduling and try with debug to see why the method behaves as it does which most probable would be from what I have mentioned above about the locks and the multiple configurations.

Reusing expensive beans in Spring Boot Tests

I am trying to improve performance of medium tests in Spring Boot.
I am using the Spring Boot - testcontainers library.
For an individual test this works really well, with a few annotations I can get access to kafka, zookeeper, and schema-registry. These are full services so it takes a few seconds to start everything up, all together setup takes about 40 seconds. The test accurately recreates a realistic deployment, it's beautifully simple.
This would be fine if it just happened once but it happens every time a Spring Context is created. That means every test that uses #MockBean incurs that 40 second cost.
I've tried refactoring into a single TestConfiguration class and referencing that. I've looked into using ContextHierarchy but I think that means I'll lose all of the Spring Boot niceties and I'll need to recreate the context (which means it won't look exactly like the context created by the production app).
Is there a better way to do this?
Spring framework already took care of this scenario.
There is a concept of caching the application context for test class/classes.
See the documentation.
Few lines from the documentation:
The Spring TestContext framework stores application contexts in a
static cache. This means that the context is literally stored in a
static variable. In other words, if tests run in separate processes,
the static cache is cleared between each test execution, which
effectively disables the caching mechanism.
So essentially you need to structure your code or context configuration in such a way that you use cached context in your desired test cases.
But use this capability wisely, if not thought through properly this could lead to undesired side-effects

Will Spring circular dependency delay application start time?

I have a monolithic Spring MVC application consists of about 1,000 beans and it will cost about two minutes to startup.
Now I am researching to find out why it startup too slow. I added a BeanFactoryPostProcessor to record the launch time and use ApplicationListener to listen to the ContextRefreshedEvent and record the time that the ApplicationContext has refreshed. Then the result shows that the application takes about 80 seconds to finish initializing the ApplicationContext.
After reviewing the code, I found there are two many circular dependencies in the code.
I am wondering if it is the circular dependencies that cause the ApplicationContext start too slow? What I can do to speed up the startup time?
The approaches I have tried include:
Check the #PostConstruct to find out if it is asynchronous.
Adjust the -Xmx and -Xms options.
Add lazy-init to the beans.
Seems not working.
Any help will be appreciated.
I assume you are using Spring Boot and then you are implicitly using the annotation component scan. So, Spring will scan each class in order to create Bean. A possible solution could be use #ComponentScan("packageToScan") instead of #ComponentScan.
However, I do not know your goal but think if you really need to speed up the startup.

Access Spring beans from a Junit Suite

I want to accomplish this - Run a background process (a Solr instance actually) that all the tests in my JUnit Suite will use.
To do this - Created a JUnit class annotated with #RunWith(Suites.class). And added a ClassRule on the Suite to start the server and stop it. Individual tests in the suite were annotated with #SpringApplicationConfiguration and #RunWith(SpringJunit4ClassRunner.class). And I also require access to some of the Beans in the Suite itself (like a spring managed settings bean). What's the best way to do this. What I tried.
Annotated individual tests with #SpringApplicationConfiguration
Had the Suite create an ApplicationContext via
SpringApplication.run and access any bean that it wants (a spring
managed Settings bean for example and use it one of ClassRules of
this Suite).
What I observed is that the ApplicationContext context gets created everytime, One for the Suite because I called SpringApplication.run and one for every test. I obviously want to avoid this and caching of the ApplicationContext between test runs also does not seem to work in this case.
So what are the best practices to handle this case.
Any suggestions/recommendations will be highly appreciated.
This is a long forgotten question, but it shown up on my google search, so I am assuming it still somehow relevant :)
I was going down on the same path but I hit so many road blocks that I decided to change my approach:
Create a JUnit runner as described here.
Change #1 to inherit SpringJUnit4ClassRunner here is an example.
Finally, annotate your Test classes with #RunWith(MyCustomRunner.class)
There you go. You can add whatever logic you need inside your runner.

Good strategy for Spring Framework end-to-end testing

So this is a rather "big" question, but what I'm trying to accomplish is the following:
I have a Spring application, MVC, JDBC (MySQL) and JSP running on tomcat.
My objective is to test the entire "stack" using a proper method.
What I have so far is Junit using Selenium to simulate an actual user interacting with the application (requires a dummy account for that), and performing different validations such as, see if element is present in the page, see if the database has a specific value or if a value matches the database.
1st concern is that this is actually using the database so it's hard to test certain scenarios. I would really like to be able to mock the database. Have it emulate specific account configs, data states etc
2nd concern is that given the fact that I use what is in the database, and data is continuously changing, it is hard to predict behavior, and therefore properly asserting
I looked at Spring Test but it allows for testing outside a servlet container, so no JSP and no Javascript testing possible.
I saw DBUtils documentation but not sure if it will help me in this case
So, to my fellow developers, I would like to ask for tips to:
Run selenium tests on top of a mocked database
Allow different configs per test
Keep compatibility with Maven/Gradle
I have started with an ordered autowire feature to support this kind of stubbing.
It's basically an idea that i took over from the Seam framework i was working with in the past but i couldnt find yet a similar thing in spring.
The idea is to have a precedence annotation (fw, app,mock,...) that will be used to resolve the current implementation of an autowired bean. This is easy already in xml but not with java config.
So we have our normal repository beans in with app precedence and a test package stubbing these classes with mock precedence.
If both are in the classpath spring would normally fail with a duplicate bean found exception. In our case the extended beanfactory simply takes the bean with the highest precedence.
Im not sure if the order annotation of spring could be used directly but i prefered to have "well defined" precedence scopes anyway, so it will be clear for our developers what this is about.
! While this is a nice approach to stub so beans for testing i would not use it to replace a database definition but rather go with an inmemory database like hsql, like some previous answers mentionned already. !

Resources