9 błędów, których należy unikać podczas programowania w Javie
Jakich błędów należy unikać podczas programowania w Javie? W poniższym artykule odpowiemy na to pytanie.
Dowiedz się, jak uruchamiać testy formularzy kontenerów w naszym artykule związanym z Javą, w którym nasz starszy programista Java pokazuje całą magię.
Używam Spring Boot w projekt aby zmniejszyć ilość szablonów. Kontenery testowe są niezależne od Spring Framework i można ich używać bez tego.
Używam Testcontainers w wersji 1.17.3, ale możesz użyć najnowszej wersji. Testy z kontenerem Postgres.
Najpierw należy zdefiniować kontener:
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() {
// nic nie rób. To jest współdzielona instancja. Niech JVM zajmie się tą operacją.
}
}
Następnie inicjalizujemy kontekst aplikacji Spring. Pobieramy całą konfigurację źródła danych z instancji kontenera i ustawiamy je jako konfigurację 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()
);
}
}
Wreszcie możemy uruchomić nasz test, a wszystko zostanie uruchomione pod maską:
@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);
}
}
Lub jeśli chcemy uruchomić niezależny test Spring, możemy użyć kontenera bezpośrednio:
@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 (wyjątek SQLException sqlException) {
assertThat((Exception) sqlException).doesNotThrowAnyException();
}
}
}
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.
