What are TestExecutionListeners, and what do they do? - spring

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)

Related

How to make pf4j plugin beans injectable into Spring app

We are trying to utilize pf4j and pf4j-spring to provide a flexible application based on Spring.
Ideally, we would like to define Spring beans (#Service, #Repository and others) in plugins and inject them in the main application.
From what I can see, it seems to fail due to timing issues. Or in other words, Springs expects the beans to be available before the PluginManager gets instantiated.
There is an example repository that illustrates the issue on GitHub.
The question would be: Can I change something, so that Spring instantiates the PluginManager first? Is there another approach to make this work?
Note: Yes, we are aware of sbp. Unfortunately, it seems to be dead, and we didn't get it working properly either.

Where should custom validation be placed in spring?

Use case:
At springboot startup I want to validate some thing regarding annotations and application.properties file. So I want spring startup to fail if the rules
are violated.
What is the standard place to do this in Spring?
I have read this article: Baeldung - Article
Two solution that I like:
CommandLineRunner/ApplicationRunner
Registering an ApplicationListener
Are these OK for validating purpose as entry point?
You can create one validator bean and put all different validation logics in different methods and annotate them by #PostConstruct
Unless your configuration is changing frequently,
and it seems likely that it should not change frequently,
you only need to perform this type of validation in an integration test.
Just write a jUnit test that loads the configuration then performs the validation.
These are often, wrongly, called unit tests (because they use jUnit) but are actually integration tests.

Should repositories in Spring Boot applications be tested directly?

Not sure if this will be considered a "legitimate question" or "purely opinion based", but is there a "best practice" with regards to directly testing a repository in a Spring Boot application? Or, should any integration testing simply target the associated service?
The reasoning for the question is simply the fact that, for the most part, a repository in a Spring Boot application contains no project-generated code. At best, it contains project-defined method signatures which Spring generates implementations for (assuming correct naming conventions).
Thanks...
If you can mess it up, you should test it. Here the opportunities to mess up can include:
Custom Queries (using #Query) might be wrong (there can be all kinds of logic mistakes or typos writing a query with no compile-time checking)
Repository methods where the query is derived from the method name might not be what you intended.
Arguments passed in, the type on the parameter list might not match the type needed in the query (nothing enforces this at compile time).
In all these cases you're not testing Spring Data JPA, you're testing the functionality you are implementing using Spring Data JPA.
Cases of using provided methods out of the box, like findOne, findAll, save, etc., where your fingerprints are not on it, don't need testing.
It's easy to test this stuff, and better to find the bugs earlier than later.
Yes, I think is a good pratice to do that. You could use #DataJpaTest annotation, it starts a in memory database. The official documentation says:
You can use the #DataJpaTest annotation to test JPA applications. By default, it configures an in-memory embedded database, scans for #Entity classes, and configures Spring Data JPA repositories. Regular #Component beans are not loaded into the ApplicationContext.
Link to the docs: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
Starting from the idea that repositories should be used only inside services and services are used to interact with the other layers of the system, I would say that testing services should be enough in the majority of cases.
I would not test standard repository methods like findAll, or findBy.., they were tested already and the purpose is not to test JPA, but rather the application.
The only repository methods that should have direct tests are the ones with custom queries. These queries may be located in a shared library and it is not efficient to write similar tests across different projects(in this case regression is a big concern)

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