Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit and re-run spring boot unit test without reloading context to speed up tests

I have a spring boot app and have written unit tests using a postgres test container (https://www.testcontainers.org/) and JUnit. The tests have the @SpringBootTest annotation which loads the context and starts up a test container before running the test.

Loading the context and starting the container takes around 15sec on my relatively old Macbook, but the test themselves are pretty fast (< 100ms each). So in a full build with 100s of tests, this does not really matter. It is a one time cost of 15sec. But developing/debugging the tests individually in an IDE becomes very slow. Every single test incurs a 15 sec startup cost.

I know IntelliJ and Springboot support hot reload of classes when the app is running. Are there similar solutions/suggestions for doing the same for unit tests ? i.e Keep the context loaded and the testcontainer(DB) running but recompile just the modified test class and run the selected test again .

like image 548
user1280213 Avatar asked May 16 '21 05:05

user1280213


People also ask

Which annotation can be used to run quick unit tests?

The @SpringBootTest annotation can be used to run quick unit tests in Spring Boot.

What is SpringBootTest annotation?

The @SpringBootTest annotation is useful when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests. We can use the webEnvironment attribute of @SpringBootTest to configure our runtime environment; we're using WebEnvironment.


2 Answers

There is a simple solution for your issue I believe. You haven't specified how exactly do you run the test container in the test, however I have a successful experience with the following approach:

For tests running locally - start postgres server on your laptop once (say at the beginning of your working day or something). It can be dockerized process or even regular postgresql installation.

During the test spring boot application doesn't really know that it interacts with test container - it gets host/port/credentials and that's it - it creates a DataSource out of these parameters.

So for your local development, you can modify the integration with the test container so that the actual test container will be launched only if there is no "LOCAL.TEST.MODE" env. variable defined (basically you can pick any name - it's not something that exists).

Then, define the ENV variable on your laptop (or you can use system property for that - whatever works for you better) and then configure spring boot's datasource to get the properties of your local installation if that system property is defined:

In a nutshell, it can be something like:

@Configuration
@ConditionalOnProperty(name = "test.local.mode", havingValue = "true", matchIfMissing = false)
public class MyDbConfig {
    @Bean
    public DataSource dataSource () {
      // create a data source initialized with local credentials
    }

}

Of course, more "clever" solution with configuration properties can be implemented, it all depends on how do you integrate with test containers and where do the actual properties for the data source initialization come from, but the idea will remain the same:

In your local env. you'll actually work with a locally installed PostgreSQL server and won't even start the test container Since all the operations in postgresql including DDL are transactional, you can put a @Transactional annotation on the test and spring will roll back all the changes done by the test so that the DB won't be full of garbage data.

As opposed to Test containers, this method has one significant advantage:

If your test fails and some data remains in the database you can check that locally because the server will remain alive. So you'll be able to connect to the db with PG Admin or something and examine the state...

Update 1

Based on op's comment

I see what you say, Basically, you've mentioned two different issues that I'll try to refer to separately

Issue 1 Application Context takes about 10-12 seconds to start.

Ok, this is something that requires investigation. The chances are that there is some bean that gets initialized slowly. So you should understand why exactly does the application starts so slowly:

The code of Spring (scanning, bean definition population, etc) works for particles of a second and usually is not a bottleneck by itself - it must be somewhere in your application.

Checking the beans startup time is kind of out of scope for this question, although there are certainly methods to do so, for example: see this thread and for newer spring versions and if you use actuator this here. So I'll assume you will figure out one way or another why does it start slowly

Anyway, what you can do with this kind of information, and how you can make the application context loading process faster? Well, obviously you can exclude the slow bean/set of beans from the configuration, maybe you don't need it at all in the tests or at least can use @MockBean instead - this highly varies depending on the actual use case. Its also possible to provide configuration in some cases that will still load that slow bean but will alter its behavior so that it won't become slow.

I can also point of "generally applicable ideas" that can help regardless your actual code base.

First of all, if you're running different test cases (multi-select tests in the IDE and run them all at once) that share exactly the same configurations, then spring boot is smart enough to not re-initialize the application context. This is called "caching of the application context in cache". Here is one of the numerous tutorials about this topic.

Another approach is using lazy beans initialization. In spring 2.2+ there is a property for that

spring:
  main:
    lazy-initialization: true

Of course, if you're not planning to use it in production, define it in src/test/resource's configuration file of your choice. spring-boot will read it as well during the test as long as it adheres to the naming convention. If you have technical issues with this. (again out of scope of the question), then consider reading this tutorial

If your spring boot is older than 2.2 you can try to do that "manually": here is how

The last direction I would like to mention is - reconsidering your test implementation. This is especially relevant if you have a big project to test. Usually, the application has separation onto layers, like services, DAO-s, controllers, you know. My point is that the testing that involves DB should be used only for the DAO's layer - this is where you test your SQL queries. The Business logic code usually doesn't require DB connection and in general, can be covered in unit tests that do not use spring at all. So instead of using @SpringBootTest annotation that starts the whole application context, you can run only the configuration of DAO(s), the chances that this will start way faster and "slow beans" belong to other parts of the application. Spring boot even has a special annotation for it (they have annotations for everything ;) ) @DataJpaTest.

This is based on the idea that the whole spring testing package is intended for integration tests only, in general, the test where you start spring is the integration test, and you'll probably prefer to work with unit tests wherever possible because they're way faster and do not use external dependencies: databases, remote services, etc.

The second issue: the schema often goes out of sync

In my current approach, the test container starts up, liquibase applies my schema and then the test is executed. Everything gets done from within the IDE, which is a bit more convenient.

I admit I haven't worked with liquibase, we've used flyway instead but I believe the answer will be the same.

In a nutshell - this will keep working like that and you don't need to change anything.

I'll explain.

Liquibase is supposed to start along with spring application context and it should apply the migrations, that's true. But before actually applying the migrations it should check whether the migrations are already applied and if the DB is in-sync it will do nothing. Flyway maintains a table in the DB for that purpose, I'm sure liquibase uses a similar mechanism.

So as long as you're not creating tables or something that test, you should be good to go:

Assuming, you're starting the Postgres server for the first time, the first test you run "at the beginning of your working day", following the aforementioned use-case will create a schema and deploy all the tables, indices, etc. with the help of liquibase migrations, and then will start the test.

However, now when you're starting the second test - the migrations will already be applied. It's equivalent to the restarting of the application itself in a non-test scenario (staging, production whatever) - the restart itself won't really apply all the migration to the DB. The same goes here...

Ok, that's the easy case, but you probably populate the data inside the tests (well, you should be ;) ) That's why I've mentioned that it's necessary to put @Transactional annotation on the test itself in the original answer.

This annotation creates a transaction before running all the code in the test and artificially rolls it back - read, removes all the data populated in the test, despite the fact that the test has passed

Now to make it more complicated, what if you create tables, alter columns on existing tables inside the test? Well, this alone will make your liquibase crazy even for production scenarios, so probably you shouldn't do that, but again putting @Transactional on the test itself helps here, because PostgreSQL's DDLs (just to clarify DDL = Data Definition Language, so I mean commands like ALTER TABLE, basically anything that changes an existing schema) commands also transactional. I know that Oracle for example didn't run DDL commands in a transaction, but things might have changed since then.

like image 50
Mark Bramnik Avatar answered Sep 29 '22 22:09

Mark Bramnik


I don't think you can keep the context loaded.

What you can do is activate reusable containers feature from testcontainers. It prevents container's destruction after test is ran.

You'll have to make sure, that your tests are idempotent, or that they remove all the changes, made to container, after completion.

In short, you should add .withReuse(true) to your container definition and add testcontainers.reuse.enable=true to ~/.testcontainers.properties (this is a file in your homedir)

Here's how I define my testcontainer to test my code with Oracle.

import org.testcontainers.containers.BindMode;
import org.testcontainers.containers.OracleContainer;

public class StaticOracleContainer {
    public static OracleContainer getContainer() {
        return LazyOracleContainer.ORACLE_CONTAINER;
    }

    private static class LazyOracleContainer {
        private static final OracleContainer ORACLE_CONTAINER = makeContainer();

        private static OracleContainer makeContainer() {
            final OracleContainer container = new OracleContainer()
                    // Username which testcontainers is going to use
                    // to find out if container is up and running
                    .withUsername("SYSTEM")
                    // Password which testcontainers is going to use
                    // to find out if container is up and running
                    .withPassword("123")
                    // Tell testcontainers, that those ports should
                    // be mapped to external ports
                    .withExposedPorts(1521, 5500)
                    // Oracle database is not going to start if less
                    // than 1gb of shared memory is available, so this is necessary
                    .withSharedMemorySize(2147483648L)
                    // This the same as giving the container
                    // -v /path/to/init_db.sql:/u01/app/oracle/scripts/startup/init_db.sql
                    // Oracle will execute init_db.sql, after container is started
                    .withClasspathResourceMapping("init_db.sql"
                            , "/u01/app/oracle/scripts/startup/init_db.sql"
                            , BindMode.READ_ONLY)
                     // Do not destroy container
                     .withReuse(true)
;

            container.start();
            return container;
        }
    }
}

As you can see this is a singleton. I need it to control testcontainers lifecycle manually, so that I could use reusable containers If you want to know how to use this singleton to add Oracle to Spring test context, you can look at my example of using testcontainers. https://github.com/poxu/testcontainers-spring-demo

There's one problem with this approach though. Testcontainers is not going to stop reusable container ever. You have to stop and destroy the container manually.

like image 26
Ilya Sazonov Avatar answered Sep 29 '22 20:09

Ilya Sazonov