Access Spring beans from a Junit Suite - spring

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.

Related

How does Spring Boot Test keep the context across multiple test suites?

I was reading through the guide for using Spring Boot Test and there was a paragraph that got me confused.
“As our profiles get richer, it's tempting to swap every now and then in our integration tests. There are convenient tools to do so, like #ActiveProfiles. However, every time we pull a test with a new profile, a new ApplicationContext gets created.”
https://www.baeldung.com/spring-tests
So it assumes that if all tests are run under the same profile, there is only one ApplicationContext created — but how is it possible? I thought that all the objects are recreated for each test suite anyway. Am I missing something?
The official reference says that it's cached.
https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/testing.html#testing-ctx-management
But how does it get loaded into the JUnit runner or Spock one across multiple test suites?
What was missing in my understanding is the fact that all the test suites are run as a part of a single program, so it's easy to cache any objects that are required by all of them, including Spring context.

Is it good practice to have separate #SpringBootApplication for (junit) test and how

I have a Spring boot application initially setting on MySQL, so far so good. However now I am trying to create more unit test for JPA / DAO layer with H2 database.
I see several online demo that in Spring it is common practice to have an applicationContext-test for testing context setting.
Is it still good practice in Spring boot 1.4?
#SpringBootApplication(scanBasePackages = {...})
public class ApplicationTest extends SpringBootServeltIntializer{
....
}
As currently there is no separate xml file holding context for testing, is above looks like a good solution? And also is there performance impact that when the application starts all context for testing are also need to loaded in memory?
Also does that mean I need to create an application.properties in test sources? Spring boot has a lot of implicit process behind, but I cannot find much texts explain about the DAO layer setting for test in Spring Boot, so any guideline is appreciated.
My preference is to not use Spring for JUnit testing at all.
JUnit tests, by definition, should be about unit testing individual classes. Spring is a DI engine for satisfying dependencies. Using the real dependencies breaks the idea of a unit test; for those I manually inject mocks.
I do that to restrict the tests to individual classes. I find that creating the Spring factory and all the application beans takes a long time. I don't want to pay that price when I have a lot of unit tests. Keeping Spring out of the mix makes my tests run faster.

What are TestExecutionListeners, and what do they do?

As far as I understand, TestExecutionListeners act like #BeforeClass methods in JUnit. What I don't understand is why I need to use DependencyInjectionTestExecutionListener, TransactionalTestExecutionListener and DirtiesContextTestExecutionListener to use DbUnitTestExecutionListener.
Normally without DbUnit, I can create and populate the database. Why suddenly do I need to use these listeners to do some CRUD for my database?
TestExecutionListeners provide various types of functionality to tests running in the Spring TestContext Framework.
If you are interested in what a particular listener does, the best way to find out is to read the Javadoc for the respective class. In addition, the Testing chapter of the Spring reference manual goes into detail about how to use each of the listeners and what they do.
In your particular case, if you're not using #DirtiesContext, then you don't need to use the DirtiesContextTestExecutionListener. As for DependencyInjectionTestExecutionListener and TransactionalTestExecutionListener, you will likely need them to inject dependencies into your test (e.g., via #Autowired, #Inject, #Resource, etc.) and for transactional tests (i.e., tests annotated with #Transactional).
Note as well that the aforementioned listeners are enabled by default. So if you've been using the Spring TestContext Framework without any custom listeners like the one for DbUnit, then you just never realized that the listeners existed. The section on TestExecutionListener configuration in the reference manual should also help clarify things. Note, however, that some features like merging and auto-detection of default listeners are only available in Spring Framework 4.1+.
Regards,
Sam (author of the Spring TestContext Framework)

Integration test without mocking the connection to the other application

I have two applications. I did integration unit tests for one of these applications, but the services that call the other application are mocked up (instead of injecting the real service, I inject another one which is mocked up).
Is there a possible way to make a real connection to the other application without having to mock it up.
A simple example would be really helpful.
Thanks in advance!
just inject the real services and do your integration test. The issue is to make sure that everything that everything that needs to be injection can be injected. Lets call your services foo and bar where foo depends on bar. if bar depends on something in the application server then starting it up during a unit might be a problem, since you are not running the app in the application server.
Integration testing is important and valuable, but it requires some careful thought to setup. The way that I have managed to setup integration testing in my application is to use spring profiles to seperate the combinations of configuration. For example I have profiles called.
production
development
container
standalone
So that way you can have a test that is launched with the proper profile that setups all the correct beans to be injected like so.
#ActiveProfile(profiles={"deveolpment","standalone"})
#RunWith ... etc other spring annotations to configure a test
public class SomeJunitTest {
}
Using profiles makes it very easy to have fine grained control over which set of beans are configured for each test.
Also for integartion testing I have found TestNG to be much easier to use that JUnit because it has features that make writing integration tests easier.

TestNG: Use ApplicationContext in multiple Test-Classes

I've written some test-cases inside a single TestNG Test which extends AbstractTestNGSpringContextTests. The ApplicationContext is correctly setup and I can use it inside my test-cases.
The problem is that the setting up of the applicationContext can take some time and I don't want to do this for every test-class I have, as this would take some time which is unnecessary from my point of view.
So my question is: Is it possible to run more than one TestNG test-class using the same Spring ApplicationContext which is setup only once?
Thanks and best regards,
Robert
How about using a #BeforeSuite?
Spring may cache and re-use ApplicationContext when you use similar locations in #ContextConfiguration annotations. See related article from Tomasz Nurkiewicz (#tomasz-nurkiewicz) at http://nurkiewicz.blogspot.com/2010/12/speeding-up-spring-integration-tests.html
Once the TestContext framework loads an ApplicationContext (or WebApplicationContext) for a test, that context will be cached and reused for all subsequent tests that declare the same unique context configuration within the same test suite.
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 execute in separate processes the static cache will be cleared between each test execution, and this will effectively disable the caching mechanism.
To benefit from the caching mechanism, all tests must run within the same process or test suite. This can be achieved by executing all tests as a group within an IDE. Similarly, when executing tests with a build framework such as Ant, Maven, or Gradle it is important to make sure that the build framework does not fork between tests. For example, if the forkMode for the Maven Surefire plug-in is set to always or pertest, the TestContext framework will not be able to cache application contexts between test classes and the build process will run significantly slower as a result.

Resources