window.pipedriveLeadboosterConfig = { base: 'leadbooster-chat.pipedrive.com', companyId: 11580370, playbookUuid: '22236db1-6d50-40c4-b48f-8b11262155be', version: 2, } ;(function () { var w = window if (w.LeadBooster) { console.warn('LeadBooster already exists') } else { w.LeadBooster = { q: [], on: function (n, h) { this.q.push({ t: 'o', n: n, h: h }) }, trigger: function (n) { this.q.push({ t: 't', n: n }) }, } } })() Quick Guide on How to Run Containers from Tests - The Codest
The Codest
  • About us
  • Services
    • Software Development
      • Frontend Development
      • Backend Development
    • Staff Augmentation
      • Frontend Developers
      • Backend Developers
      • Data Engineers
      • Cloud Engineers
      • QA Engineers
      • Other
    • It Advisory
      • Audit & Consulting
  • Industries
    • Fintech & Banking
    • E-commerce
    • Adtech
    • Healthtech
    • Manufacturing
    • Logistics
    • Automotive
    • IOT
  • Value for
    • CEO
    • CTO
    • Delivery Manager
  • Our team
  • Case Studies
  • Know How
    • Blog
    • Meetups
    • Webinars
    • Resources
Careers Get in touch
  • About us
  • Services
    • Software Development
      • Frontend Development
      • Backend Development
    • Staff Augmentation
      • Frontend Developers
      • Backend Developers
      • Data Engineers
      • Cloud Engineers
      • QA Engineers
      • Other
    • It Advisory
      • Audit & Consulting
  • Value for
    • CEO
    • CTO
    • Delivery Manager
  • Our team
  • Case Studies
  • Know How
    • Blog
    • Meetups
    • Webinars
    • Resources
Careers Get in touch
Back arrow GO BACK
2022-08-16
Software Development

Quick Guide on How to Run Containers from Tests

Bartlomiej Kuczyński

Learn how to run containers form tests in our Java related article where our senior java developer shows all the magic.

I use Spring Boot in the project to reduce boilerplate. Test containers are independent of Spring Framework and you can use them without that.

I use Testcontainers version 1.17.3, but feel free to use the newest one. Tests with Postgres container.

First define container:

public class Postgres13TC extends PostgreSQLContainer<Postgres13TC> {
  private static final Postgres13TC TC = new Postgres13TC();

  private Postgres13TC() {
    super("postgres:13.2");
  }

  public static Postgres13TC getInstance() {
    return TC;
  }

  @Override
  public void start() {
    super.start();
    System.setProperty("DB_URL", TC.getJdbcUrl());
    System.setProperty("DB_USERNAME", TC.getUsername());
    System.setProperty("DB_PASSWORD", TC.getPassword());
  }

  @Override
  public void stop() {
    // do nothing. This is shared instance. Let JVM handle this operation.
  }
}

Then initialize Spring application context. We get all data source configuration from container instance and set them as Spring configuration:

public class ContainerInit implements ApplicationContextInitializer<ConfigurableApplicationContext> {

  public static Postgres13TC postgres13TC;

  static {
    postgres13TC = Postgres13TC.getInstance();
    postgres13TC.start();
  }

  @Override
  public void initialize(ConfigurableApplicationContext applicationContext) {
    TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
        applicationContext,
        "spring.datasource.url=" + postgres13TC.getJdbcUrl(),
        "spring.datasource.username=" + postgres13TC.getUsername(),
        "spring.datasource.password=" + postgres13TC.getPassword(),
        "db.host=" + postgres13TC.getHost(),
        "db.port=" + postgres13TC.getMappedPort(postgres13TC.POSTGRESQL_PORT),
        "db.name=" + postgres13TC.getDatabaseName(),
        "db.username=" + postgres13TC.getUsername(),
        "db.password=" + postgres13TC.getPassword()
    );
  }
}

Finally, we can run our test, and everything will be started under the hood:

@SpringBootTest(webEnvironment = RANDOM_PORT)
@AutoConfigureTestDatabase(replace = NONE)
@ContextConfiguration(initializers = ContainerInit.class)
@Testcontainers
class DummyRepositoryTest {

  @Autowired
  private DummyRepository dummyRepository;

  @Test
  void shouldReturnDummy() {
    var byId = dummyRepository.getById(10L);
    var expected = new Dummy();
    expected.setId(10L);
    assertThat(byId).completes().emitsCount(1).emits(expected);
  }
}

Or if we want to run Spring independent test, we can use container directly:

@Testcontainers
class SimpleDbTest {

  @Container
  private static final Postgres13TC postgres13TC = Postgres13TC.getInstance();

  @Test
  void testConnection() {
    assumeThat(postgres13TC.isRunning());
    var connectionProps = new Properties();
    connectionProps.put("user", postgres13TC.getUsername());
    connectionProps.put("password", postgres13TC.getPassword());
    try (Connection connection = DriverManager.getConnection(postgres13TC.getJdbcUrl(),
        connectionProps)) {
    var resultSet = connection.prepareStatement("Select 1").executeQuery();
    resultSet.next();
    assertThat(resultSet.getInt(1)).isEqualTo(1);
    } catch (SQLException sqlException) {
    assertThat((Exception) sqlException).doesNotThrowAnyException();
    }
  }
}

Summing up

Testcontainers are very easy-to-use tools that help us to create integration tests that use Docker containers. That gives us more flexibility and increases development speed. Proper setup of test configuration reduces the time needed to board new developers. They don’t need to set up all dependencies, just run the written tests with selected configuration files.

cooperation banner

Related articles

Software Development

9 Mistakes to Avoid While Programming in Java

What mistakes should be avoided while programming in Java? In the following piece we answers this question.

The Codest
Rafal Sawicki Java Developer
Enterprise & Scaleups Solutions

How Java Can Support Your Business?

Before we start, I would like to remind you about one important thing. Java is not only a programming language.

Bartlomiej Kuczynski
Enterprise & Scaleups Solutions

The Right Way to Find Top Java Developers

Finding the perfect Java developer can be a daunting task. As the market demand for such professionals grows at an astonishing pace, available sources for talent search can sometimes seem...

The Codest
Grzegorz Rozmus Java Unit Leader

Subscribe to our knowledge base and stay up to date on the expertise from the IT sector.

    About us

    The Codest – International software development company with tech hubs in Poland.

    United Kingdom - Headquarters

    • Office 303B, 182-184 High Street North E6 2JA
      London, England

    Poland - Local Tech Hubs

    • Fabryczna Office Park, Aleja
      Pokoju 18, 31-564 Kraków
    • Brain Embassy, Konstruktorska
      11, 02-673 Warsaw, Poland

      The Codest

    • Home
    • About us
    • Services
    • Case Studies
    • Know How
    • Careers
    • Dictionary

      Services

    • It Advisory
    • Software Development
    • Backend Development
    • Frontend Development
    • Staff Augmentation
    • Backend Developers
    • Cloud Engineers
    • Data Engineers
    • Other
    • QA Engineers

      Resources

    • Facts and Myths about Cooperating with External Software Development Partner
    • From the USA to Europe: Why do American startups decide to relocate to Europe
    • Tech Offshore Development Hubs Comparison: Tech Offshore Europe (Poland), ASEAN (Philippines), Eurasia (Turkey)
    • What are the top CTOs and CIOs Challenges?
    • The Codest
    • The Codest
    • The Codest
    • Privacy policy
    • Website terms of use

    Copyright © 2025 by The Codest. All rights reserved.

    en_USEnglish
    de_DEGerman sv_SESwedish da_DKDanish nb_NONorwegian fiFinnish fr_FRFrench pl_PLPolish arArabic it_ITItalian jaJapanese ko_KRKorean es_ESSpanish nl_NLDutch etEstonian elGreek en_USEnglish