I have my beans reading and writing some data on disk while working and configuring and would like to work with these files during tests.
For example, I would like to prepare some files on disk before context configuration and after of it configuration but before tests.
How to use run some code at these moments?
If you are using #RunWith(SpringJUnit4ClassRunner.class) then you could provide a different class, based on Spring's, and override methods to execute what you want before the context is initialized. But normally you can do the setup and tear down in the test itself by using #BeforeClass and #AfterClass.
Related
I'm working on an integration with an older library so that it can use Spring Boot testing, and for that I need to register a certain bean very early in the process, so that an ApplicationListener<ApplicationReadyEvent> can add a PropertySource to the Environment.
This works fine in the normal startup, but when using the #SpringBootTest annotation I need to be able to inspect the TestContext very early and add it to the testing BootstrapContext, so that the application listener can access it also in the integration tests.
But I can't find a good way to add bean instances to the test BootstrapContext apart from specifying an initializer class in the spring.factories files, or am I missing something here?
I have been looking into using #BootstrapWith and subclassing SpringBootContextBootstrapper, but can't seem to find a way to add some kind of BootstrapregistryInitializer-like functions?
I have such JUnit 5 test and becuase of test speed I need to disable creating Hazelcast instances while running test. Is there some way how to disable Hazelcast for one particular test?
#SpringBootTest
#RunWith(SpringRunner.class)
class MemoryTradeCommunicatorTest {
// test cases....
}
There are three main ways to approach your problem. I'll assume you just need to disable Hazelcast and that you're using Spring Boot though you don't mention it explicitly.
As Dmitrii mentions, you can mock the bean that provides the Hazelcast instance. Be aware that you'll probably need to split your configuration into multiple fragments so that you can import the beans required in your tests.
You can use Spring profiles. You'd need to create a test profile and create a mock Hazelcast instance inside it. The implementation depends a lot on how you create the real Hazelcast instance (Spring Boot or manually).
Spring Boot creates the Hazelcast instance because of auto-configuration classes. You can prevent this behavior by excluding specific classes. In your case, you'd launch your tests with spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration
You can use #Import for loading only required beans and mock your Hazelcast bean something like that:
#RunWith(SpringRunner.class)
#Import(value = {MemoryTradeCommunicator.class})
#MockBean
private CacheManager cacheManager;
class MemoryTradeCommunicatorTest {
// test cases....
}
Where CacheManager is your Hazelcast realization. Also, don't forget to declare your other needed bean into #Import
I want to use junit with a spring context in order to write some integration tests.
These tests will just do a series of calls to rest endpoints and assert the responses. Somethink like what is described here but with a spring context in order to get what I need in unit test (like resttemplate and a user creation service). In order to not instantiate a context for each run I will use something like:
#ContextConfiguration(locations = {"classpath:test-context.xml"})
#RunWith(SpringJUnit4ClassRunner.class)
Because I have ContextConfiguration with the same context, this will stay cached during all tests run. I'm trying to add a yaml to this in order to have different envs (UAT, prod) but nothing I tried so far works. Is there a way to import the YML in context xml?
You can use #TestPropertySource to load different properties/yaml file
#TestPropertySource(locations="classpath:test.properties")
I am trying to implement integration tests for my Tomcat application, but my issue is that the application is launched separately from the tests so the tests cannot access the application context and neither the database.
My idea is running the tests "within" the running application, so I can #Autowire EntityManager and check for instance the state of the database during testing or even create database entities for testing.
My only idea of doing this is to actually run the application programmatically from the tests as ClassPathXmlApplicationContext("applicationContext.xml") and the access the Context. This would work, but it would be very hard for debugging as we wouldn't be able to use Hotswapping during the testing. Also I guess the server would be stopped as soon as the tests would end. I guess that is not the best and correct solution.
EDIT:
My question was probably unclear, so I will try to clarify.
I have a Tomcat application with Spring and Hibernate. The Spring beans and Hibernate database connection is initialised when the Tomcat application is started. The issue is how to run the tests of the active Spring beans from methods annotated with #Test in src/test/java which are started separately.
Consider this class:
#Component
class MyRepository {
#Autowired
EntityManager em;
#Transactional
public void myMethod(MyEntity entity) {
// do some job with entity
...
em.flush();
}
}
This class will be initialised with Tomcat as a MyRepository bean.
To test it, I cannot just call new MyRepository().myMethod(...) - I need to access the bean. The issue is accessing the bean from the #Test method:
#Test
void testMyRepository() {
Item item = ...
// then use the repository to handle the entity
context.getBean(MyRepository.class).myMethod(item);
// then assert the state of the database
context.getBean(EntityManager.class).find(Item.class, ...) ...
}
I can probably get the context in the initialisation of the tests with
ApplicationContext context = ClassPathXmlApplicationContext("applicationContext.xml");
But it would mean launching the whole application each time the tests are started. The better solution would be if the application could run separately from the tests.
Hope my problem is more clear now.
I would suggest you to use the SpringRunner to start the Spring application context and perform your tests on that running instance. You can customize the context the way it doesn't contain parts you don't want to tests and you can create mocks for components that require some external resources (REST clients and such). Take a look at the Spring docs or Spring Boot docs.
If multiple tests use the same Spring context configuration, the context is started just once and reused. So it's good to have it's configuration in a parent class of your tests. You can autowire any Spring bean into your test and test it.
You can use an in-memory database (such as H2) instead of a production one, so your tests are not dependent on an external infrastructure. To initialize the database, use tools like Flyway or Liquibase. To clear the database before each test, you can use the #Sql annotation.
You can find many examples of projects with such tests, for example my own demo.
If you want to test an external system, I would suggest something like JMeter.
Unfortunately you cant mirror your classes and use them in your tests. Thats a big disadvantage of web services. They always depend on user / machine interaction. With a lot of effort you can extract the functionality of the essential classes or methods and construct test scenarios etc. with jUnit.
The Overview of your possibilities:
special drivers and placeholders
you can use a logger with detailed log-level and file output. Then you created scenarios with the expected result and compare it with your log files.
Capture replay tools. They record your exection and replay them for monitoring.
I can also recommend using Selenium for the frontend tests.
Hope it helped.
I have developed my application and I have a .properties file containing several key-value properties.
In my code I inject said properties like this:
#Value("${services.host}${services.name}")
private String hostname;
I am searching for a way to check every #Value inside of my code so to make sure that every property will be solved at runtime. Something like simulating my application startup.
Is it possible?
Yes, you can create a JUnit test class that loads your application context (just like your production code would) and then execute a test method that verifies that your property values have been injected.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {AppConfig.class})
public class SpringApplicationTest {
#Autowired
private MyServiceBean serviceBean;
#Test
public void shouldExecuteServiceBean_andProduceExpectedOutcome() {
//TODO test setup
serviceBean.doSomething()
//TODO assert output
}
}
In this example MyServiceBean.java is a class that would be executed from your Main class, so that you are testing the end-to-end logic of your application, including all of the spring dependency injections. Think of it as your "happy path" test scenario. I always include at least one test like this in my projects, to ensure that all of the spring injections are correct and load without error. You wan't to catch the errors before you build and deploy your code.
In the example above AppConfig.java is the same Spring configuration class you use when your code is deployed. You probably want to add another configuration class that overrides some properties/beans specifically for testing only.
#ContextConfiguration(classes = {AppConfig.class, TestConfig.class})
Using a test only class, you can mock out any dependencies that make testing difficult (i.e. use an in-memory database), and also override properties so you can test against "localhost" rather than another service which may or may not be available (so long as you can create an equivalent localhost service in your test setup).
Note: If you are finding it difficult to test your application due to too many dependencies, or external dependencies that cannot be swapped out easily, the pain you are feeling is a good guide to start thinking about how to change your architecture to support ease of testing. You also can just test portions of your application using the above concepts.