9 errori da evitare durante la programmazione in Java
Quali sono gli errori da evitare durante la programmazione in Java? Nel pezzo che segue rispondiamo a questa domanda.
 
                
Scoprite come eseguire i test dei moduli dei contenitori nel nostro articolo dedicato a Java, in cui il nostro sviluppatore java senior mostra tutta la magia.
Uso Spring Boot nel progetto per ridurre il boilerplate. I contenitori di test sono indipendenti da Struttura Spring e si possono usare anche senza.
Io uso la versione 1.17.3 di Testcontainers, ma potete usare anche la più recente. Test con contenitore Postgres.
Definire innanzitutto il contenitore:
public class Postgres13TC extends PostgreSQLContainer {
  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() {
    // non fa nulla. Questa è un'istanza condivisa. Lasciamo che sia la JVM a gestire questa operazione.
  }
}Quindi inizializzare il contesto applicativo di Spring. Otteniamo tutte le configurazioni dell'origine dati dall'istanza del contenitore e le impostiamo come configurazione di Spring:
public class ContainerInit implements ApplicationContextInitializer {
  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()
    );
  }
}Infine, possiamo eseguire il nostro test e tutto sarà avviato sotto il cofano:
@SpringBootTest(webEnvironment = RANDOM_PORT)
@AutoConfigureTestDatabase(replace = NONE)
@ContextConfiguration(initializers = ContainerInit.class)
@Contenitori di test
class DummyRepositoryTest {
  @Autowired
  private DummyRepository dummyRepository;
  @Test
  void shouldReturnDummy() {
    var byId = dummyRepository.getById(10L);
    var expected = new Dummy();
    expected.setId(10L);
    assertThat(byId).complet().emitsCount(1).emits(expected);
  }
}Oppure, se vogliamo eseguire test indipendenti da Spring, possiamo usare direttamente il contenitore:
@Contenitori di test
classe SimpleDbTest {
  @contenitore
  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();
    }
  }
}I Testcontainer sono strumenti molto semplici da usare che ci aiutano a creare test di integrazione che utilizzano i container Docker. Questo ci offre maggiore flessibilità e aumenta la velocità di sviluppo. L'impostazione corretta della configurazione dei test riduce il tempo necessario per i nuovi sviluppatori. Non devono configurare tutte le dipendenze, ma solo eseguire i test scritti con i file di configurazione selezionati.
