repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java
spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineReader.java
package com.baeldung.taskletsvschunks.chunks; import com.baeldung.taskletsvschunks.model.Line; import com.baeldung.taskletsvschunks.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.item.ItemReader; public class LineReader implements ItemReader<Line>, StepExecutionListener { private final Logger logger = LoggerFactory.getLogger(LineReader.class); private FileUtils fu; @Override public void beforeStep(StepExecution stepExecution) { fu = new FileUtils("taskletsvschunks/input/tasklets-vs-chunks.csv"); logger.debug("Line Reader initialized."); } @Override public Line read() { Line line = fu.readLine(); if (line != null) logger.debug("Read line: " + line); return line; } @Override public ExitStatus afterStep(StepExecution stepExecution) { fu.closeReader(); logger.debug("Line Reader ended."); return ExitStatus.COMPLETED; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/utils/FileUtils.java
spring-batch/src/main/java/com/baeldung/taskletsvschunks/utils/FileUtils.java
package com.baeldung.taskletsvschunks.utils; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; import com.baeldung.taskletsvschunks.model.Line; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class FileUtils { private final Logger logger = LoggerFactory.getLogger(FileUtils.class); private String fileName; private CSVReader CSVReader; private CSVWriter CSVWriter; private FileReader fileReader; private FileWriter fileWriter; private File file; public FileUtils(String fileName) { this.fileName = fileName; } public Line readLine() { try { if (CSVReader == null) initReader(); String[] line = CSVReader.readNext(); if (line == null) return null; return new Line(line[0], LocalDate.parse(line[1], DateTimeFormatter.ofPattern("MM/dd/yyyy"))); } catch (Exception e) { logger.error("Error while reading line in file: " + this.fileName); return null; } } public void writeLine(Line line) { try { if (CSVWriter == null) initWriter(); String[] lineStr = new String[2]; lineStr[0] = line.getName(); lineStr[1] = line .getAge() .toString(); CSVWriter.writeNext(lineStr); } catch (Exception e) { logger.error("Error while writing line in file: " + this.fileName); } } private void initReader() throws Exception { ClassLoader classLoader = this .getClass() .getClassLoader(); if (file == null) file = new File(classLoader .getResource(fileName) .getFile()); if (fileReader == null) fileReader = new FileReader(file); if (CSVReader == null) CSVReader = new CSVReader(fileReader); } private void initWriter() throws Exception { if (file == null) { file = new File(fileName); file.createNewFile(); } if (fileWriter == null) fileWriter = new FileWriter(file, true); if (CSVWriter == null) CSVWriter = new CSVWriter(fileWriter); } public void closeWriter() { try { CSVWriter.close(); fileWriter.close(); } catch (IOException e) { logger.error("Error while closing writer."); } } public void closeReader() { try { CSVReader.close(); fileReader.close(); } catch (IOException e) { logger.error("Error while closing reader."); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java
spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/ChunksConfig.java
package com.baeldung.taskletsvschunks.config; import com.baeldung.taskletsvschunks.chunks.LineProcessor; import com.baeldung.taskletsvschunks.chunks.LineReader; import com.baeldung.taskletsvschunks.chunks.LinesWriter; import com.baeldung.taskletsvschunks.model.Line; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.PlatformTransactionManager; @Configuration public class ChunksConfig { @Bean public ItemReader<Line> itemReader() { return new LineReader(); } @Bean public ItemProcessor<Line, Line> itemProcessor() { return new LineProcessor(); } @Bean public ItemWriter<Line> itemWriter() { return new LinesWriter(); } @Bean(name = "processLines") protected Step processLines(JobRepository jobRepository, PlatformTransactionManager transactionManager, ItemReader<Line> reader, ItemProcessor<Line, Line> processor, ItemWriter<Line> writer) { return new StepBuilder("processLines", jobRepository).<Line, Line> chunk(2, transactionManager) .reader(reader) .processor(processor) .writer(writer) .build(); } @Bean(name = "chunksJob") public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new JobBuilder("chunksJob", jobRepository) .start(processLines(jobRepository, transactionManager, itemReader(), itemProcessor(), itemWriter())) .build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java
spring-batch/src/main/java/com/baeldung/taskletsvschunks/config/TaskletsConfig.java
package com.baeldung.taskletsvschunks.config; import com.baeldung.taskletsvschunks.tasklets.LinesProcessor; import com.baeldung.taskletsvschunks.tasklets.LinesReader; import com.baeldung.taskletsvschunks.tasklets.LinesWriter; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.PlatformTransactionManager; @Configuration public class TaskletsConfig { @Bean public LinesReader linesReader() { return new LinesReader(); } @Bean public LinesProcessor linesProcessor() { return new LinesProcessor(); } @Bean public LinesWriter linesWriter() { return new LinesWriter(); } @Bean protected Step readLines(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("readLines", jobRepository) .tasklet(linesReader(), transactionManager) .build(); } @Bean protected Step processLines(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("processLines", jobRepository) .tasklet(linesProcessor(), transactionManager) .build(); } @Bean protected Step writeLines(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("writeLines", jobRepository) .tasklet(linesWriter(), transactionManager) .build(); } @Bean public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new JobBuilder("taskletsJob", jobRepository) .start(readLines(jobRepository, transactionManager)) .next(processLines(jobRepository, transactionManager)) .next(writeLines(jobRepository, transactionManager)) .build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesProcessor.java
spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesProcessor.java
package com.baeldung.taskletsvschunks.tasklets; import com.baeldung.taskletsvschunks.model.Line; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.repeat.RepeatStatus; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.List; public class LinesProcessor implements Tasklet, StepExecutionListener { private final Logger logger = LoggerFactory.getLogger(LinesProcessor.class); private List<Line> lines; @Override public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { for (Line line : lines) { long age = ChronoUnit.YEARS.between(line.getDob(), LocalDate.now()); logger.debug("Calculated age " + age + " for line " + line.toString()); line.setAge(age); } return RepeatStatus.FINISHED; } @Override public void beforeStep(StepExecution stepExecution) { ExecutionContext executionContext = stepExecution .getJobExecution() .getExecutionContext(); this.lines = (List<Line>) executionContext.get("lines"); logger.debug("Lines Processor initialized."); } @Override public ExitStatus afterStep(StepExecution stepExecution) { logger.debug("Lines Processor ended."); return ExitStatus.COMPLETED; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesWriter.java
spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesWriter.java
package com.baeldung.taskletsvschunks.tasklets; import com.baeldung.taskletsvschunks.model.Line; import com.baeldung.taskletsvschunks.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.repeat.RepeatStatus; import java.util.List; public class LinesWriter implements Tasklet, StepExecutionListener { private final Logger logger = LoggerFactory.getLogger(LinesWriter.class); private List<Line> lines; private FileUtils fu; @Override public void beforeStep(StepExecution stepExecution) { ExecutionContext executionContext = stepExecution .getJobExecution() .getExecutionContext(); this.lines = (List<Line>) executionContext.get("lines"); fu = new FileUtils("output.csv"); logger.debug("Lines Writer initialized."); } @Override public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { for (Line line : lines) { fu.writeLine(line); logger.debug("Wrote line " + line.toString()); } return RepeatStatus.FINISHED; } @Override public ExitStatus afterStep(StepExecution stepExecution) { fu.closeWriter(); logger.debug("Lines Writer ended."); return ExitStatus.COMPLETED; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java
spring-batch/src/main/java/com/baeldung/taskletsvschunks/tasklets/LinesReader.java
package com.baeldung.taskletsvschunks.tasklets; import com.baeldung.taskletsvschunks.model.Line; import com.baeldung.taskletsvschunks.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; import java.util.ArrayList; import java.util.List; public class LinesReader implements Tasklet, StepExecutionListener { private final Logger logger = LoggerFactory.getLogger(LinesReader.class); private List<Line> lines; private FileUtils fu; @Override public void beforeStep(StepExecution stepExecution) { lines = new ArrayList<>(); fu = new FileUtils("taskletsvschunks/input/tasklets-vs-chunks.csv"); logger.debug("Lines Reader initialized."); } @Override public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { Line line = fu.readLine(); while (line != null) { lines.add(line); logger.debug("Read line: " + line.toString()); line = fu.readLine(); } return RepeatStatus.FINISHED; } @Override public ExitStatus afterStep(StepExecution stepExecution) { fu.closeReader(); stepExecution .getJobExecution() .getExecutionContext() .put("lines", this.lines); logger.debug("Lines Reader ended."); return ExitStatus.COMPLETED; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningManualTest.java
libraries-testing/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningManualTest.java
package com.baeldung.awaitility; import org.awaitility.Duration; import org.junit.Before; import org.junit.Test; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; import static org.awaitility.Awaitility.fieldIn; import static org.awaitility.Awaitility.given; import static org.awaitility.Awaitility.setDefaultPollDelay; import static org.awaitility.Awaitility.setDefaultPollInterval; import static org.awaitility.Awaitility.setDefaultTimeout; import static org.awaitility.proxy.AwaitilityClassProxy.to; import static org.hamcrest.Matchers.equalTo; public class AsyncServiceLongRunningManualTest { private AsyncService asyncService; @Before public void setUp() { asyncService = new AsyncService(); } @Test public void givenAsyncService_whenInitialize_thenInitOccurs1() { asyncService.initialize(); Callable<Boolean> isInitialized = asyncService::isInitialized; await().until(isInitialized); } @Test public void givenAsyncService_whenInitialize_thenInitOccurs2() { asyncService.initialize(); Callable<Boolean> isInitialized = asyncService::isInitialized; await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS).atMost(Duration.FIVE_SECONDS).with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS).until(isInitialized); } @Test public void givenAsyncService_whenInitialize_thenInitOccurs_withDefualts() { setDefaultPollInterval(10, TimeUnit.MILLISECONDS); setDefaultPollDelay(Duration.ZERO); setDefaultTimeout(Duration.ONE_MINUTE); asyncService.initialize(); await().until(asyncService::isInitialized); } @Test public void givenAsyncService_whenInitialize_thenInitOccurs_withProxy() { asyncService.initialize(); await().untilCall(to(asyncService).isInitialized(), equalTo(true)); } @Test public void givenAsyncService_whenInitialize_thenInitOccurs3() { asyncService.initialize(); await().until(fieldIn(asyncService).ofType(boolean.class).andWithName("initialized"), equalTo(true)); } @Test public void givenValue_whenAddValue_thenValueAdded() { asyncService.initialize(); await().until(asyncService::isInitialized); long value = 5; asyncService.addValue(value); await().until(asyncService::getValue, equalTo(value)); } @Test public void givenAsyncService_whenGetValue_thenExceptionIgnored() { asyncService.initialize(); given().ignoreException(IllegalStateException.class).await().atMost(Duration.FIVE_SECONDS).atLeast(Duration.FIVE_HUNDRED_MILLISECONDS).until(asyncService::getValue, equalTo(0L)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java
libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java
package com.baeldung.dbunit; import org.dbunit.Assertion; import org.dbunit.IDatabaseTester; import org.dbunit.JdbcDatabaseTester; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITable; import org.dbunit.dataset.filter.DefaultColumnFilter; import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; import org.dbunit.operation.DatabaseOperation; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import static com.baeldung.dbunit.ConnectionSettings.JDBC_DRIVER; import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; import static com.baeldung.dbunit.ConnectionSettings.USER; import static org.assertj.core.api.Assertions.assertThat; import static org.dbunit.Assertion.assertEquals; @RunWith(JUnit4.class) public class OldSchoolDbUnitTest { private static IDatabaseTester tester = null; private Connection connection; @BeforeClass public static void setUp() throws Exception { tester = initDatabaseTester(); } private static IDatabaseTester initDatabaseTester() throws Exception { JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); tester.setDataSet(initDataSet()); tester.setSetUpOperation(DatabaseOperation.REFRESH); tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); return tester; } private static IDataSet initDataSet() throws Exception { try (InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { return new FlatXmlDataSetBuilder().build(is); } } @Before public void setup() throws Exception { tester.onSetup(); connection = tester.getConnection().getConnection(); } @After public void tearDown() throws Exception { tester.onTearDown(); } @Test public void givenDataSet_whenSelect_thenFirstTitleIsGreyTShirt() throws Exception { ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); assertThat(rs.next()).isTrue(); assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); } @Test public void givenDataSet_whenInsert_thenGetResultsAreStillEqualIfIgnoringColumnsWithDifferentProduced() throws Exception { String[] excludedColumns = { "id", "produced" }; try (InputStream is = getClass().getClassLoader() .getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { // given IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); ITable expectedTable = DefaultColumnFilter .excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); // when connection.createStatement() .executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); // then IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = DefaultColumnFilter .excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); Assertion.assertEquals(expectedTable, actualTable); } } @Test public void givenDataSet_whenDelete_thenItemIsRemoved() throws Exception { try (InputStream is = OldSchoolDbUnitTest.class.getClassLoader() .getResourceAsStream("dbunit/items_exp_delete.xml")) { // given ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); // when connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); // then IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); assertEquals(expectedTable, actualTable); } } @Test public void givenDataSet_whenProductIgnoredAndDelete_thenItemIsRemoved() throws Exception { try (InputStream is = OldSchoolDbUnitTest.class.getClassLoader() .getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { // given ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); // when connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); // then IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); assertEquals(expectedTable, actualTable); } } @Test public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception { try (InputStream is = OldSchoolDbUnitTest.class.getClassLoader() .getResourceAsStream("dbunit/items_exp_rename.xml")) { // given ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); // when connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); // then IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); assertEquals(expectedTable, actualTable); } } @Test public void givenDataSet_whenUpdateWithNoProduced_thenItemHasNewName() throws Exception { try (InputStream is = OldSchoolDbUnitTest.class.getClassLoader() .getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { // given ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[] { "produced" }); // when connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); // then IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); assertEquals(expectedTable, actualTable); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java
libraries-testing/src/test/java/com/baeldung/dbunit/ConnectionSettings.java
package com.baeldung.dbunit; public class ConnectionSettings { public static final String JDBC_DRIVER = org.h2.Driver.class.getName(); public static final String JDBC_URL = "jdbc:h2:mem:default;MODE=LEGACY;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:dbunit/schema.sql'"; public static final String USER = "sa"; public static final String PASSWORD = ""; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java
libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java
package com.baeldung.dbunit; import org.dbunit.Assertion; import org.dbunit.DataSourceBasedDBTestCase; import org.dbunit.assertion.DiffCollectingFailureHandler; import org.dbunit.assertion.Difference; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITable; import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; import org.dbunit.operation.DatabaseOperation; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.platform.commons.logging.Logger; import org.junit.platform.commons.logging.LoggerFactory; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; import static com.baeldung.dbunit.ConnectionSettings.USER; import static java.util.stream.Collectors.joining; import static org.assertj.core.api.Assertions.assertThat; import static org.dbunit.Assertion.assertEqualsIgnoreCols; @RunWith(JUnit4.class) public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { private static final Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); private Connection connection; @Override protected DataSource getDataSource() { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(JDBC_URL); dataSource.setUser(USER); dataSource.setPassword(PASSWORD); return dataSource; } @Override protected IDataSet getDataSet() throws Exception { try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { return new FlatXmlDataSetBuilder().build(resourceAsStream); } } @Override protected DatabaseOperation getSetUpOperation() { return DatabaseOperation.REFRESH; } @Override protected DatabaseOperation getTearDownOperation() { return DatabaseOperation.DELETE_ALL; } @Before public void setUp() throws Exception { super.setUp(); connection = getConnection().getConnection(); } @After public void tearDown() throws Exception { super.tearDown(); } @Test public void givenDataSet_whenSelect_thenFirstTitleIsGreyTShirt() throws SQLException { ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); assertThat(rs.next()).isTrue(); assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); } @Test public void givenDataSetEmptySchema_whenDataSetCreated_thenTablesAreEqual() throws Exception { IDataSet expectedDataSet = getDataSet(); ITable expectedTable = expectedDataSet.getTable("CLIENTS"); IDataSet databaseDataSet = getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("CLIENTS"); Assertion.assertEquals(expectedTable, actualTable); } @Test public void givenDataSet_whenInsert_thenTableHasNewClient() throws Exception { try (InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-user.xml")) { // given IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); ITable expectedTable = expectedDataSet.getTable("CLIENTS"); Connection conn = getDataSource().getConnection(); // when conn.createStatement() .executeUpdate("INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); ITable actualData = getConnection() .createQueryTable("result_name", "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); // then assertEqualsIgnoreCols(expectedTable, actualData, new String[] { "id" }); } } @Test public void givenDataSet_whenDelete_thenItemIsDeleted() throws Exception { try (InputStream is = DataSourceDBUnitTest.class.getClassLoader() .getResourceAsStream("dbunit/items_exp_delete.xml")) { // given ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); // when connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); // then IDataSet databaseDataSet = getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); Assertion.assertEquals(expectedTable, actualTable); } } @Test public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception { try (InputStream is = DataSourceDBUnitTest.class.getClassLoader() .getResourceAsStream("dbunit/items_exp_rename.xml")) { // given ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); IDataSet databaseDataSet = getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); Assertion.assertEquals(expectedTable, actualTable); } } @Test public void givenDataSet_whenInsertUnexpectedData_thenFail() throws Exception { try (InputStream is = getClass().getClassLoader() .getResourceAsStream("dbunit/expected-multiple-failures.xml")) { // given IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); ITable expectedTable = expectedDataSet.getTable("ITEMS"); Connection conn = getDataSource().getConnection(); DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); // when conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); ITable actualData = getConnection().createDataSet().getTable("ITEMS"); // then Assertion.assertEquals(expectedTable, actualData, collectingHandler); if (!collectingHandler.getDiffList().isEmpty()) { String message = (String) collectingHandler.getDiffList().stream() .map(d -> formatDifference((Difference) d)).collect(joining("\n")); logger.error(() -> message); } } } private static String formatDifference(Difference diff) { return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff .getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff .getActualValue(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java
libraries-testing/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java
package com.baeldung.pact; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import au.com.dius.pact.consumer.MockServer; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.consumer.junit5.PactConsumerTestExt; import au.com.dius.pact.consumer.junit5.PactTestFor; import au.com.dius.pact.model.RequestResponsePact; @ExtendWith(PactConsumerTestExt.class) @PactTestFor(providerName = "test_provider", hostInterface="localhost") public class PactConsumerDrivenContractUnitTest { @Pact(provider="test_provider", consumer = "test_consumer") public RequestResponsePact createPact(PactDslWithProvider builder) { Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); return builder .given("test GET") .uponReceiving("GET REQUEST") .path("/pact") .method("GET") .willRespondWith() .status(200) .headers(headers) .body("{\"condition\": true, \"name\": \"tom\"}") .given("test POST") .uponReceiving("POST REQUEST") .method("POST") .headers(headers) .body("{\"name\": \"Michael\"}") .path("/pact") .willRespondWith() .status(201) .toPact(); } @Test @PactTestFor void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody(MockServer mockServer) { // when ResponseEntity<String> response = new RestTemplate().getForEntity(mockServer.getUrl() + "/pact", String.class); // then assertThat(response.getStatusCode().value()).isEqualTo(200); assertThat(response.getHeaders().get("Content-Type").contains("application/json")).isTrue(); assertThat(response.getBody()).contains("condition", "true", "name", "tom"); // and HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); String jsonBody = "{\"name\": \"Michael\"}"; // when ResponseEntity<String> postResponse = new RestTemplate().exchange(mockServer.getUrl() + "/pact", HttpMethod.POST, new HttpEntity<>(jsonBody, httpHeaders), String.class); // then assertThat(postResponse.getStatusCode().value()).isEqualTo(201); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/pact/PactProviderLiveTest.java
libraries-testing/src/test/java/com/baeldung/pact/PactProviderLiveTest.java
package com.baeldung.pact; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.SpringApplication; import org.springframework.web.context.ConfigurableWebApplicationContext; import com.baeldung.pact.config.MainApplication; import au.com.dius.pact.provider.junit.Provider; import au.com.dius.pact.provider.junit.State; import au.com.dius.pact.provider.junit.loader.PactFolder; import au.com.dius.pact.provider.junit5.HttpTestTarget; import au.com.dius.pact.provider.junit5.PactVerificationContext; import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider; @Provider("test_provider") @PactFolder("target/mypacts") public class PactProviderLiveTest { private static ConfigurableWebApplicationContext application; @BeforeAll public static void start() { application = (ConfigurableWebApplicationContext) SpringApplication.run(MainApplication.class); } @BeforeEach void before(PactVerificationContext context) { context.setTarget(new HttpTestTarget("localhost", 8082, "/spring-rest")); } @TestTemplate @ExtendWith(PactVerificationInvocationContextProvider.class) void pactVerificationTestTemplate(PactVerificationContext context) { context.verifyInteraction(); } @State("test GET") public void toGetState() { } @State("test POST") public void toPostState() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/archunit/smurfs/SmurfsArchManualTest.java
libraries-testing/src/test/java/com/baeldung/archunit/smurfs/SmurfsArchManualTest.java
package com.baeldung.archunit.smurfs; import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.lang.ArchRule; import com.tngtech.archunit.library.Architectures.LayeredArchitecture; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; import static com.tngtech.archunit.library.Architectures.layeredArchitecture; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; public class SmurfsArchManualTest { @Test public void givenPresentationLayerClasses_thenWrongCheckFails() { JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs"); ArchRule r1 = classes() .that() .resideInAPackage("..presentation..") .should().onlyDependOnClassesThat() .resideInAPackage("..service.."); assertThrows(AssertionError.class, ()-> r1.check(jc)) ; } @Test public void givenPresentationLayerClasses_thenCheckWithFrameworkDependenciesSuccess() { JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs"); ArchRule r1 = classes() .that() .resideInAPackage("..presentation..") .should().onlyDependOnClassesThat() .resideInAnyPackage("..service..", "java..", "javax..", "org.springframework.."); r1.check(jc); } @Test public void givenPresentationLayerClasses_thenNoPersistenceLayerAccess() { JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs"); ArchRule r1 = noClasses() .that() .resideInAPackage("..presentation..") .should().dependOnClassesThat() .resideInAPackage("..persistence.."); r1.check(jc); } @Test public void givenApplicationClasses_thenNoLayerViolationsShouldExist() { JavaClasses jc = new ClassFileImporter().importPackages("com.baeldung.archunit.smurfs"); LayeredArchitecture arch = layeredArchitecture() // Define layers .layer("Presentation").definedBy("..presentation..") .layer("Service").definedBy("..service..") .layer("Persistence").definedBy("..persistence..") // Add constraints .whereLayer("Presentation").mayNotBeAccessedByAnyLayer() .whereLayer("Service").mayOnlyBeAccessedByLayers("Presentation") .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service"); arch.check(jc); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/modelassert/ModelAssertUnitTest.java
libraries-testing/src/test/java/com/baeldung/modelassert/ModelAssertUnitTest.java
package com.baeldung.modelassert; import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; import uk.org.webcompere.modelassert.json.dsl.nodespecific.tree.WhereDsl; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static uk.org.webcompere.modelassert.json.JsonAssertions.*; import static uk.org.webcompere.modelassert.json.PathWildCard.ANY; import static uk.org.webcompere.modelassert.json.PathWildCard.ANY_SUBTREE; import static uk.org.webcompere.modelassert.json.Patterns.GUID_PATTERN; class ModelAssertUnitTest { private static final String ACTUAL_JSON = "{" + "\"name\": \"Baeldung\"," + "\"isOnline\": true," + "\"topics\": [ \"Java\", \"Spring\", \"Kotlin\", \"Scala\", \"Linux\" ]" + "}"; private static final Path PATH_TO_EXPECTED = Paths.get("src", "test", "resources", "modelassert", "baeldung.json"); public interface DataService { boolean isUserLoggedIn(String userDetails); } private DataService mockDataService = mock(DataService.class); @Test void givenJson_thenNameIsBaeldung() { assertJson(ACTUAL_JSON) .at("/name").isText("Baeldung"); } @Test void givenJson_thenSecondTopicIsSpring() { assertJson(ACTUAL_JSON) .at("/topics/1").isText("Spring"); } @Test void givenJson_thenCanMakeMultipleAssertions() { assertJson(ACTUAL_JSON) .at("/name").isText("Baeldung") .at("/topics/1").isText("Spring"); } @Test void givenCompareByString_thenFailsOnFormatting() throws IOException { String expected = String.join("\n", Files.readAllLines(PATH_TO_EXPECTED)); assertThatThrownBy(() -> assertThat(ACTUAL_JSON).isEqualTo(expected)) .isInstanceOf(AssertionFailedError.class); } @Test void givenTwoIdenticalTreesInDifferentFormat_thenPassesWithIsEqualTo() { assertJson(ACTUAL_JSON) .isEqualTo(PATH_TO_EXPECTED); } @Test void givenMap_thenCanCompareToYaml() { Map<String, String> map = new HashMap<>(); map.put("name", "baeldung"); assertJson(map) .isEqualToYaml("name: baeldung"); } @Test void givenYaml_thenCanCompareToMap() { Map<String, String> map = new HashMap<>(); map.put("name", "baeldung"); assertYaml("name: baeldung") .isEqualTo(map); } @Test void canProduceHamcrestMatcher() { Matcher<String> matcher = json().at("/name").hasValue("Baeldung"); MatcherAssert.assertThat(ACTUAL_JSON, matcher); } @Test void givenJson_thenCanAssertWithMatcherAssert() { MatcherAssert.assertThat(ACTUAL_JSON, json() .at("/name").hasValue("Baeldung") .at("/topics/1").isText("Spring")); } @Test void givenUserIsOnline_thenIsLoggedIn() { given(mockDataService.isUserLoggedIn(argThat(json() .at("/isOnline").isTrue() .toArgumentMatcher()))) .willReturn(true); assertThat(mockDataService.isUserLoggedIn(ACTUAL_JSON)) .isTrue(); verify(mockDataService) .isUserLoggedIn(argThat(json() .at("/name").isText("Baeldung") .toArgumentMatcher())); } @Test void givenDocument_canMakeSeveralRootNodeAssertions() { assertJson(ACTUAL_JSON) .isNotNull() .isNotNumber() .isObject() .containsKey("name"); } @Test void givenDocument_canAssertArray() { assertJson(ACTUAL_JSON) .at("/topics").hasSize(5); } @Test void givenDocument_canAssertBooleanByType() { assertJson(ACTUAL_JSON) .at("/isOnline").booleanNode().isTrue(); } @Test void givenTextNode_canAssertContents() { assertJson(ACTUAL_JSON) .at("/name").textContains("ael"); } @Test void givenTextNode_canMatchWithRegex() { assertJson(ACTUAL_JSON) .at("/name").matches("[A-Z].+"); } @Test void givenNumberNode_canTestRange() { assertJson("{count: 12}") .at("/count").isBetween(1, 25); } @Test void givenNumberNode_canTestDouble() { assertJson("{height: 6.3}") .at("/height").isGreaterThanDouble(6.0); } @Test void givenNumberNode_canTestDoubleEquals() { assertJson("{height: 6.3}") .at("/height").isNumberEqualTo(6.3); } @Test void givenArrayNode_canTestContains() { assertJson(ACTUAL_JSON) .at("/topics").isArrayContaining("Scala", "Spring"); } @Test void givenArrayNode_canTestContainsExactlyInAnyOrder() { assertJson(ACTUAL_JSON) .at("/topics").isArrayContainingExactlyInAnyOrder("Scala", "Spring", "Java", "Linux", "Kotlin"); } @Test void givenArrayNode_canTestContainsExactly() { assertJson(ACTUAL_JSON) .at("/topics").isArrayContainingExactly("Java", "Spring", "Kotlin", "Scala", "Linux"); } @Test void givenArrayNode_thenCanAssertBySubtree() { assertJson(ACTUAL_JSON) .at("/topics").isEqualTo("[ \"Java\", \"Spring\", \"Kotlin\", \"Scala\", \"Linux\" ]"); } @Test void givenKeyOrderIsDifferent_canStillBeEqual() { String actualJson = "{a:{d:3, c:2, b:1}}"; String expectedJson = "{a:{b:1, c:2, d:3}}"; assertJson(actualJson) .where().keysInAnyOrder() .isEqualTo(expectedJson); } @Test void givenKeyOrderIsDifferentInA_canStillBeEqual() { String actualJson = "{a:{d:3, c:2, b:1}}"; String expectedJson = "{a:{b:1, c:2, d:3}}"; assertJson(actualJson) .where() .at("/a").keysInAnyOrder() .isEqualTo(expectedJson); } @Test void givenElementOrderIsDifferent_canStillBeEqual() { String actualJson = "{a:[1, 2, 3, 4, 5]}"; String expectedJson = "{a:[5, 4, 3, 2, 1]}"; assertJson(actualJson) .where().arrayInAnyOrder() .isEqualTo(expectedJson); } @Test void givenActualHasExtraValue_thenIgnoreIt() { String actualJson = "{user:{name: \"Baeldung\", url:\"http://www.baeldung.com\"}}"; String expectedJson = "{user:{name: \"Baeldung\"}}"; assertJson(actualJson) .where().at("/user/url").isIgnored() .isEqualTo(expectedJson); } @Test void givenActualHasIdGUIDS_thenIgnoreThem() { String actualJson = "{user:{credentials:[" + "{id:\"a7dc2567-3340-4a3b-b1ab-9ce1778f265d\",role:\"Admin\"}," + "{id:\"09da84ba-19c2-4674-974f-fd5afff3a0e5\",role:\"Sales\"}]}}"; String expectedJson = "{user:{credentials:" + "[{id:\"???\",role:\"Admin\"}," + "{id:\"???\",role:\"Sales\"}]}}"; assertJson(actualJson) .where() .path("user","credentials", ANY, "id").isIgnored() .isEqualTo(expectedJson); } @Test void givenActualHasIdGUIDS_thenMatchThemByRegexAndSubtree() { String actualJson = "{user:{credentials:[" + "{id:\"a7dc2567-3340-4a3b-b1ab-9ce1778f265d\",role:\"Admin\"}," + "{id:\"09da84ba-19c2-4674-974f-fd5afff3a0e5\",role:\"Sales\"}]}}"; String expectedJson = "{user:{credentials:" + "[{id:\"???\",role:\"Admin\"}," + "{id:\"???\",role:\"Sales\"}]}}"; assertJson(actualJson) .where() .path(ANY_SUBTREE, "id").matches(GUID_PATTERN) .isEqualTo(expectedJson); } @Test void givenActualHasIdGUIDS_thenMatchThemByRegexAndSubtreeUsingStandardPattern() { String actualJson = "{user:{credentials:[" + "{id:\"a7dc2567-3340-4a3b-b1ab-9ce1778f265d\",role:\"Admin\"}," + "{id:\"09da84ba-19c2-4674-974f-fd5afff3a0e5\",role:\"Sales\"}]}}"; String expectedJson = "{user:{credentials:" + "[{id:\"???\",role:\"Admin\"}," + "{id:\"???\",role:\"Sales\"}]}}"; assertJson(actualJson) .where() .configuredBy(where -> idsAreGuids(where)) .isEqualTo(expectedJson); } private static <T> WhereDsl<T> idsAreGuids(WhereDsl<T> where) { return where.path(ANY_SUBTREE, "id").matches(GUID_PATTERN); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/hamcrest/Cat.java
libraries-testing/src/test/java/com/baeldung/hamcrest/Cat.java
package com.baeldung.hamcrest; public class Cat extends Animal { public Cat() { super("cat", false, "meow"); } public String makeSound() { return getSound(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/hamcrest/Animal.java
libraries-testing/src/test/java/com/baeldung/hamcrest/Animal.java
package com.baeldung.hamcrest; public class Animal { String name; boolean wild; String sound; public Animal(String name, boolean wild, String sound) { super(); this.name = name; this.wild = wild; this.sound = sound; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isWild() { return wild; } public void setWild(boolean wild) { this.wild = wild; } public String getSound() { return sound; } public void setSound(String sound) { this.sound = sound; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/hamcrest/Person.java
libraries-testing/src/test/java/com/baeldung/hamcrest/Person.java
package com.baeldung.hamcrest; public class Person { String name; String address; public Person(String personName, String personAddress) { name = personName; address = personAddress; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { String str="[address:"+address+",name:"+name+"]"; return str; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/hamcrest/IsPositiveInteger.java
libraries-testing/src/test/java/com/baeldung/hamcrest/IsPositiveInteger.java
package com.baeldung.hamcrest; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class IsPositiveInteger extends TypeSafeMatcher<Integer> { public void describeTo(Description description) { description.appendText("a positive integer"); } @Factory public static Matcher<Integer> isAPositiveInteger() { return new IsPositiveInteger(); } @Override protected boolean matchesSafely(Integer integer) { return integer > 0; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/test/java/com/baeldung/hamcrest/HamcrestMatcherUnitTest.java
libraries-testing/src/test/java/com/baeldung/hamcrest/HamcrestMatcherUnitTest.java
package com.baeldung.hamcrest; import org.junit.Test; import java.util.*; import static com.baeldung.hamcrest.IsPositiveInteger.isAPositiveInteger; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.beans.HasProperty.hasProperty; import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs; import static org.hamcrest.collection.IsArrayContaining.hasItemInArray; import static org.hamcrest.collection.IsArrayContainingInAnyOrder.arrayContainingInAnyOrder; import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining; import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.hamcrest.collection.IsIn.isIn; import static org.hamcrest.collection.IsIn.isOneOf; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.collection.IsMapContaining.hasKey; import static org.hamcrest.collection.IsMapContaining.hasValue; import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.Every.everyItem; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsSame.sameInstance; import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.core.StringEndsWith.endsWith; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.object.HasToString.hasToString; import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith; import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; import static org.hamcrest.text.IsEmptyString.isEmptyString; import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase; import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace; import static org.hamcrest.text.StringContainsInOrder.stringContainsInOrder; public class HamcrestMatcherUnitTest { @Test public void given2Strings_whenEqual_thenCorrect() { String a = "foo"; String b = "FOO"; assertThat(a, equalToIgnoringCase(b)); } @Test public void givenBean_whenHasValue_thenCorrect() { Person person = new Person("Baeldung", "New York"); assertThat(person, hasProperty("name")); } @Test public void givenBean_whenHasCorrectValue_thenCorrect() { Person person = new Person("Baeldung", "New York"); assertThat(person, hasProperty("address", equalTo("New York"))); } @Test public void given2Beans_whenHavingSameValues_thenCorrect() { Person person1 = new Person("Baeldung", "New York"); Person person2 = new Person("Baeldung", "New York"); assertThat(person1, samePropertyValuesAs(person2)); } @Test public void givenAList_whenChecksSize_thenCorrect() { List<String> hamcrestMatchers = Arrays.asList("collections", "beans", "text", "number"); assertThat(hamcrestMatchers, hasSize(4)); } @Test public void givenArray_whenChecksSize_thenCorrect() { String[] hamcrestMatchers = { "collections", "beans", "text", "number" }; assertThat(hamcrestMatchers, arrayWithSize(4)); } @Test public void givenAListAndValues_whenChecksListForGivenValues_thenCorrect() { List<String> hamcrestMatchers = Arrays.asList("collections", "beans", "text", "number"); assertThat(hamcrestMatchers, containsInAnyOrder("beans", "text", "collections", "number")); } @Test public void givenAListAndValues_whenChecksListForGivenValuesWithOrder_thenCorrect() { List<String> hamcrestMatchers = Arrays.asList("collections", "beans", "text", "number"); assertThat(hamcrestMatchers, contains("collections", "beans", "text", "number")); } @Test public void givenArrayAndValue_whenValueFoundInArray_thenCorrect() { String[] hamcrestMatchers = { "collections", "beans", "text", "number" }; assertThat(hamcrestMatchers, hasItemInArray("text")); } @Test public void givenValueAndArray_whenValueIsOneOfArrayElements_thenCorrect() { String[] hamcrestMatchers = { "collections", "beans", "text", "number" }; assertThat("text", isOneOf(hamcrestMatchers)); } @Test public void givenArrayAndValues_whenValuesFoundInArray_thenCorrect() { String[] hamcrestMatchers = { "collections", "beans", "text", "number" }; assertThat( hamcrestMatchers, arrayContainingInAnyOrder("beans", "collections", "number", "text")); } @Test public void givenArrayAndValues_whenValuesFoundInArrayInOrder_thenCorrect() { String[] hamcrestMatchers = { "collections", "beans", "text", "number" }; assertThat(hamcrestMatchers, arrayContaining("collections", "beans", "text", "number")); } @Test public void givenCollection_whenEmpty_thenCorrect() { List<String> emptyList = new ArrayList<>(); assertThat(emptyList, empty()); } @Test public void givenValueAndArray_whenValueFoundInArray_thenCorrect() { String[] array = new String[] { "collections", "beans", "text", "number" }; assertThat("beans", isIn(array)); } @Test public void givenMapAndKey_whenKeyFoundInMap_thenCorrect() { Map<String, String> map = new HashMap<>(); map.put("blogname", "baeldung"); assertThat(map, hasKey("blogname")); } @Test public void givenMapAndEntry_whenEntryFoundInMap_thenCorrect() { Map<String, String> map = new HashMap<>(); map.put("blogname", "baeldung"); assertThat(map, hasEntry("blogname", "baeldung")); } @Test public void givenMapAndValue_whenValueFoundInMap_thenCorrect() { Map<String, String> map = new HashMap<>(); map.put("blogname", "baeldung"); assertThat(map, hasValue("baeldung")); } @Test public void givenString_whenEmpty_thenCorrect() { String str = ""; assertThat(str, isEmptyString()); } @Test public void givenString_whenEmptyOrNull_thenCorrect() { String str = null; assertThat(str, isEmptyOrNullString()); } @Test public void given2Strings_whenEqualRegardlessWhiteSpace_thenCorrect() { String str1 = "text"; String str2 = " text "; assertThat(str1, equalToIgnoringWhiteSpace(str2)); } @Test public void givenString_whenContainsGivenSubstring_thenCorrect() { String str = "calligraphy"; assertThat(str, stringContainsInOrder(Arrays.asList("call", "graph"))); } @Test public void givenBean_whenToStringReturnsRequiredString_thenCorrect() { Person person = new Person("Barrack", "Washington"); String str = person.toString(); assertThat(person, hasToString(str)); } @Test public void given2Classes_whenOneInheritsFromOther_thenCorrect() { assertThat(Cat.class, typeCompatibleWith(Animal.class)); } @Test public void given2Strings_whenIsEqualRegardlessWhiteSpace_thenCorrect() { String str1 = "text"; String str2 = " text "; assertThat(str1, is(equalToIgnoringWhiteSpace(str2))); } @Test public void given2Strings_whenIsNotEqualRegardlessWhiteSpace_thenCorrect() { String str1 = "text"; String str2 = " texts "; assertThat(str1, not(equalToIgnoringWhiteSpace(str2))); } @Test public void given2Strings_whenNotEqual_thenCorrect() { String str1 = "text"; String str2 = "texts"; assertThat(str1, not(str2)); } @Test public void given2Strings_whenIsEqual_thenCorrect() { String str1 = "text"; String str2 = "text"; assertThat(str1, is(str2)); } @Test public void givenAStrings_whenContainsAnotherGivenString_thenCorrect() { String str1 = "calligraphy"; String str2 = "call"; assertThat(str1, containsString(str2)); } @Test public void givenAString_whenEndsWithAnotherGivenString_thenCorrect() { String str1 = "calligraphy"; String str2 = "phy"; assertThat(str1, endsWith(str2)); } @Test public void givenAString_whenStartsWithAnotherGivenString_thenCorrect() { String str1 = "calligraphy"; String str2 = "call"; assertThat(str1, startsWith(str2)); } @Test public void given2Objects_whenSameInstance_thenCorrect() { Cat cat = new Cat(); assertThat(cat, sameInstance(cat)); } @Test public void givenAnObject_whenInstanceOfGivenClass_thenCorrect() { Cat cat = new Cat(); assertThat(cat, instanceOf(Cat.class)); } @Test public void givenList_whenEachElementGreaterThan0_thenCorrect() { List<Integer> list = Arrays.asList(1, 2, 3); int baseCase = 0; assertThat(list, everyItem(greaterThan(baseCase))); } @Test public void givenString_whenNotNull_thenCorrect() { String str = "notnull"; assertThat(str, notNullValue()); } @Test public void givenString_whenMeetsAnyOfGivenConditions_thenCorrect() { String str = "calligraphy"; String start = "call"; String end = "foo"; assertThat(str, anyOf(startsWith(start), containsString(end))); } @Test public void givenString_whenMeetsAllOfGivenConditions_thenCorrect() { String str = "calligraphy"; String start = "call"; String end = "phy"; assertThat(str, allOf(startsWith(start), endsWith(end))); } @Test public void givenInteger_whenAPositiveValue_thenCorrect() { int num = 1; assertThat(num, isAPositiveInteger()); } @Test public void givenAnInteger_whenGreaterThan0_thenCorrect() { int num = 1; assertThat(num, greaterThan(0)); } @Test public void givenAnInteger_whenGreaterThanOrEqTo5_thenCorrect() { int num = 5; assertThat(num, greaterThanOrEqualTo(5)); } @Test public void givenAnInteger_whenLessThan0_thenCorrect() { int num = -1; assertThat(num, lessThan(0)); } @Test public void givenAnInteger_whenLessThanOrEqTo5_thenCorrect() { assertThat(-1, lessThanOrEqualTo(5)); } @Test public void givenADouble_whenCloseTo_thenCorrect() { assertThat(1.2, closeTo(1, 0.5)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/main/java/com/baeldung/awaitility/AsyncService.java
libraries-testing/src/main/java/com/baeldung/awaitility/AsyncService.java
package com.baeldung.awaitility; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; public class AsyncService { private final int DELAY = 1000; private final int INIT_DELAY = 2000; private final AtomicLong value = new AtomicLong(0); private final Executor executor = Executors.newFixedThreadPool(4); private volatile boolean initialized = false; void initialize() { executor.execute(() -> { sleep(INIT_DELAY); initialized = true; }); } boolean isInitialized() { return initialized; } void addValue(long val) { throwIfNotInitialized(); executor.execute(() -> { sleep(DELAY); value.addAndGet(val); }); } public long getValue() { throwIfNotInitialized(); return value.longValue(); } private void sleep(int delay) { try { Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } } private void throwIfNotInitialized() { if (!initialized) { throw new IllegalStateException("Service is not initialized"); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/main/java/com/baeldung/pact/config/MainApplication.java
libraries-testing/src/main/java/com/baeldung/pact/config/MainApplication.java
package com.baeldung.pact.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @EnableAutoConfiguration @ComponentScan("com.baeldung.pact") public class MainApplication implements WebMvcConfigurer { public static void main(final String[] args) { SpringApplication.run(MainApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/main/java/com/baeldung/pact/web/controller/PactController.java
libraries-testing/src/main/java/com/baeldung/pact/web/controller/PactController.java
package com.baeldung.pact.web.controller; import java.util.ArrayList; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.baeldung.pact.web.dto.PactDto; @RestController public class PactController { List<PactDto> pacts = new ArrayList<>(); @GetMapping(value = "/pact", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public PactDto getPact() { return new PactDto(true, "tom"); } @PostMapping("/pact") @ResponseStatus(HttpStatus.CREATED) public void createPact(PactDto pact) { pacts.add(pact); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/main/java/com/baeldung/pact/web/dto/PactDto.java
libraries-testing/src/main/java/com/baeldung/pact/web/dto/PactDto.java
package com.baeldung.pact.web.dto; public class PactDto { private boolean condition; private String name; public PactDto() { } public PactDto(boolean condition, String name) { super(); this.condition = condition; this.name = name; } public boolean isCondition() { return condition; } public void setCondition(boolean condition) { this.condition = condition; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/service/SmurfsService.java
libraries-testing/src/main/java/com/baeldung/archunit/smurfs/service/SmurfsService.java
package com.baeldung.archunit.smurfs.service; import java.util.List; import java.util.stream.Collectors; import org.springframework.stereotype.Component; import com.baeldung.archunit.smurfs.persistence.SmurfsRepository; import com.baeldung.archunit.smurfs.persistence.domain.Smurf; import com.baeldung.archunit.smurfs.service.dto.SmurfDTO; @Component public class SmurfsService { private SmurfsRepository repository; public SmurfsService(SmurfsRepository repository) { this.repository = repository; } public List<SmurfDTO> findAll() { return repository.findAll() .stream() .map(SmurfsService::toDTO) .collect(Collectors.toList()); } public static SmurfDTO toDTO(Smurf smurf) { return new SmurfDTO(smurf.getName(),smurf.isComic(), smurf.isCartoon()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/service/dto/SmurfDTO.java
libraries-testing/src/main/java/com/baeldung/archunit/smurfs/service/dto/SmurfDTO.java
package com.baeldung.archunit.smurfs.service.dto; public class SmurfDTO { private String name; private boolean comic; private boolean cartoon; public SmurfDTO() {} public SmurfDTO(String name, boolean comic, boolean cartoon) { this.name = name; this.comic = comic; this.cartoon = cartoon; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isComic() { return comic; } public void setCommic(boolean comic) { this.comic = comic; } public boolean isCartoon() { return cartoon; } public void setCartoon(boolean cartoon) { this.cartoon = cartoon; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/presentation/SmurfsController.java
libraries-testing/src/main/java/com/baeldung/archunit/smurfs/presentation/SmurfsController.java
package com.baeldung.archunit.smurfs.presentation; import java.util.List; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.baeldung.archunit.smurfs.service.SmurfsService; import com.baeldung.archunit.smurfs.service.dto.SmurfDTO; @RequestMapping(value = "/smurfs", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @RestController public class SmurfsController { private SmurfsService smurfs; public SmurfsController(SmurfsService smurfs) { this.smurfs = smurfs; } @GetMapping public List<SmurfDTO> getSmurfs() { return smurfs.findAll(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/SmurfsRepository.java
libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/SmurfsRepository.java
package com.baeldung.archunit.smurfs.persistence; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import com.baeldung.archunit.smurfs.persistence.domain.Smurf; import static java.util.stream.Collectors.toList; public class SmurfsRepository { private static Map<String,Smurf> smurfs = Collections.synchronizedMap(new TreeMap<>()); static { // Just a few here. A full list can be found // at https://smurfs.fandom.com/wiki/List_of_Smurf_characters smurfs.put("Papa", new Smurf("Papa", true, true)); smurfs.put("Actor", new Smurf("Actor", true, true)); smurfs.put("Alchemist", new Smurf("Alchemist", true, true)); smurfs.put("Archeologist", new Smurf("Archeologist", true, true)); smurfs.put("Architect", new Smurf("Architect", true, true)); smurfs.put("Baby", new Smurf("Baby", true, true)); smurfs.put("Baker", new Smurf("Baker", true, true)); } public List<Smurf> findAll() { return Collections.unmodifiableList(smurfs.values().stream().collect(toList())); } public Optional<Smurf> findByName(String name) { return Optional.of(smurfs.get(name)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/domain/Smurf.java
libraries-testing/src/main/java/com/baeldung/archunit/smurfs/persistence/domain/Smurf.java
package com.baeldung.archunit.smurfs.persistence.domain; public class Smurf { private String name; private boolean comic; private boolean cartoon; public Smurf(String name, boolean comic, boolean cartoon) { this.name = name; this.comic = comic; this.cartoon = cartoon; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isComic() { return comic; } public void setCommic(boolean comic) { this.comic = comic; } public boolean isCartoon() { return cartoon; } public void setCartoon(boolean cartoon) { this.cartoon = cartoon; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apollo/src/main/java/com/example/demo/DemoController.java
apollo/src/main/java/com/example/demo/DemoController.java
package com.example.demo; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; @RestController @RequestMapping("/config") public class DemoController { // We're not using JDBC, but this is the example property from the article. @Value("${spring.datasource.url}") private String someValue; @GetMapping public String get() { return "Hello, " + someValue; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apollo/src/main/java/com/example/demo/DemoApplication.java
apollo/src/main/java/com/example/demo/DemoApplication.java
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; @SpringBootApplication @EnableApolloConfig public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/BagUnitTest.java
libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/BagUnitTest.java
package com.baeldung.commons.collections; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.SortedBag; import org.apache.commons.collections4.bag.*; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; public class BagUnitTest { @Test public void givenMultipleCopies_whenAdded_theCountIsKept() { Bag<Integer> bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); assertThat(bag.getCount(1), equalTo(2)); } @Test public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() { Collection<Integer> collection = new ArrayList<>(); // Collection contract defines that add() should return true assertThat(collection.add(9), is(true)); // Even when element is already in the collection collection.add(1); assertThat(collection.add(1), is(true)); Bag<Integer> bag = new HashBag<>(); // Bag returns true on adding a new element assertThat(bag.add(9), is(true)); bag.add(1); // But breaks the contract with false when it has to increment the count assertThat(bag.add(1), is(not(true))); } @Test public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() { Bag<Integer> bag = CollectionBag.collectionBag(new HashBag<>()); bag.add(1); // This time the behavior is compliant to the Java Collection assertThat(bag.add(1), is((true))); } @Test public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() { Bag<Integer> bag = new HashBag<>(); // Adding 1 for 5 times bag.add(1, 5); assertThat(bag.getCount(1), equalTo(5)); } @Test public void givenMultipleCopies_whenRemove_allAreRemoved() { Bag<Integer> bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 })); // From 3 we delete 1, 2 remain bag.remove(3, 1); assertThat(bag.getCount(3), equalTo(2)); // From 2 we delete all bag.remove(1); assertThat(bag.getCount(1), equalTo(0)); } @Test public void givenTree_whenDuplicateElementsAdded_thenSort() { TreeBag<Integer> bag = new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })); assertThat(bag.first(), equalTo(1)); assertThat(bag.getCount(bag.first()), equalTo(2)); assertThat(bag.last(), equalTo(7)); assertThat(bag.getCount(bag.last()), equalTo(3)); } @Test public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() { SortedBag<Integer> bag = CollectionSortedBag.collectionSortedBag(new TreeBag<>()); bag.add(1); assertThat(bag.add(1), is((true))); } @Test public void givenSortedBag_whenDuplicateElementsAdded_thenSort() { SynchronizedSortedBag<Integer> bag = SynchronizedSortedBag.synchronizedSortedBag(new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }))); assertThat(bag.first(), equalTo(1)); assertThat(bag.getCount(bag.first()), equalTo(2)); assertThat(bag.last(), equalTo(7)); assertThat(bag.getCount(bag.last()), equalTo(3)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java
libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java
package com.baeldung.commons.collections; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.bidimap.DualHashBidiMap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class BidiMapUnitTest { @Test public void givenKeyValue_whenPut_thenAddEntryToMap() { BidiMap<String, String> map = new DualHashBidiMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); assertEquals(map.size(), 2); } @Test public void whenInverseBidiMap_thenInverseKeyValue() { BidiMap<String, String> map = new DualHashBidiMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); BidiMap<String, String> rMap = map.inverseBidiMap(); assertTrue(rMap.containsKey("value1") && rMap.containsKey("value2")); } @Test public void givenValue_whenRemoveValue_thenRemoveMatchingMapEntry() { BidiMap<String, String> map = new DualHashBidiMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.removeValue("value2"); assertFalse(map.containsKey("key2")); } @Test public void givenValue_whenGetKey_thenMappedKey() { BidiMap<String, String> map = new DualHashBidiMap<>(); map.put("key1", "value1"); assertEquals(map.getKey("value1"), "key1"); } @Test public void givenKeyValue_whenAddValue_thenReplaceFirstKey() { BidiMap<String, String> map = new DualHashBidiMap<>(); map.put("key1", "value1"); map.put("key2", "value1"); assertEquals(map.size(), 1); assertFalse(map.containsKey("key1")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java
libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java
package com.baeldung.commons.collections; import org.apache.commons.collections4.SetUtils; import org.apache.commons.collections4.set.TransformedSet; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class SetUtilsUnitTest { @Test(expected = IllegalArgumentException.class) public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() { Set<String> sourceSet = new HashSet<>(); sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1")); Set<String> validatingSet = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L")); validatingSet.add("Err Source2"); } @Test public void givenTwoSets_whenDifference_thenSetView() { Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5)); Set<Integer> b = new HashSet<>(Arrays.asList(1, 2)); SetUtils.SetView<Integer> result = SetUtils.difference(a, b); assertTrue(result.size() == 1 && result.contains(5)); } @Test public void givenTwoSets_whenUnion_thenUnionResult() { Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5)); Set<Integer> b = new HashSet<>(Arrays.asList(1, 2)); Set<Integer> expected = new HashSet<>(Arrays.asList(1, 2, 5)); SetUtils.SetView<Integer> union = SetUtils.union(a, b); assertTrue(SetUtils.isEqualSet(expected, union)); } @Test public void givenTwoSets_whenIntersection_thenIntersectionResult() { Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5)); Set<Integer> b = new HashSet<>(Arrays.asList(1, 2)); Set<Integer> expected = new HashSet<>(Arrays.asList(1, 2)); SetUtils.SetView<Integer> intersect = SetUtils.intersection(a, b); assertTrue(SetUtils.isEqualSet(expected, intersect)); } @Test public void givenSet_whenTransformedSet_thenTransformedResult() { Set<Integer> a = SetUtils.transformedSet(new HashSet<>(), (e) -> e * 2); a.add(2); assertEquals(a.toArray()[0], 4); Set<Integer> source = new HashSet<>(Arrays.asList(1)); Set<Integer> newSet = TransformedSet.transformedSet(source, (e) -> e * 2); assertEquals(newSet.toArray()[0], 2); assertEquals(source.toArray()[0], 2); } @Test public void givenTwoSet_whenDisjunction_thenDisjunctionSet() { Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5)); Set<Integer> b = new HashSet<>(Arrays.asList(1, 2, 3)); SetUtils.SetView<Integer> result = SetUtils.disjunction(a, b); assertTrue(result.toSet().contains(5) && result.toSet().contains(3)); } @Test public void givenSet_when_OrderedSet_thenMaintainElementOrder() { Set<Integer> set = new HashSet<>(Arrays.asList(10, 1, 5)); System.out.println("unordered set: " + set); Set<Integer> orderedSet = SetUtils.orderedSet(new HashSet<>()); orderedSet.addAll(Arrays.asList(10, 1, 5)); System.out.println("ordered set = " + orderedSet); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java
libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java
package com.baeldung.commons.collections; import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.TransformerUtils; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.hamcrest.Matchers.is; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; import static org.hamcrest.collection.IsMapWithSize.anEmptyMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class MapUtilsUnitTest { private String[][] color2DArray = new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } }; private String[] color1DArray = new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" }; private Map<String, String> colorMap; @Before public void createMap() { this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color2DArray); } @Test public void whenCreateMapFrom2DArray_theMapIsCreated() { this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color2DArray); assertThat(this.colorMap, is(aMapWithSize(this.color2DArray.length))); assertThat(this.colorMap, hasEntry("RED", "#FF0000")); assertThat(this.colorMap, hasEntry("GREEN", "#00FF00")); assertThat(this.colorMap, hasEntry("BLUE", "#0000FF")); } @Test public void whenCreateMapFrom1DArray_theMapIsCreated() { this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color1DArray); assertThat(this.colorMap, is(aMapWithSize(this.color1DArray.length / 2))); assertThat(this.colorMap, hasEntry("RED", "#FF0000")); assertThat(this.colorMap, hasEntry("GREEN", "#00FF00")); assertThat(this.colorMap, hasEntry("BLUE", "#0000FF")); } @Test public void whenVerbosePrintMap_thenMustPrintFormattedMap() { MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap); } @Test public void whenGetKeyNotPresent_thenMustReturnDefaultValue() { String defaultColorStr = "COLOR_NOT_FOUND"; String color = MapUtils.getString(this.colorMap, "BLACK", defaultColorStr); assertEquals(color, defaultColorStr); } @Test public void whenGetOnNullMap_thenMustReturnDefaultValue() { String defaultColorStr = "COLOR_NOT_FOUND"; String color = MapUtils.getString(null, "RED", defaultColorStr); assertEquals(color, defaultColorStr); } @Test public void whenInvertMap_thenMustReturnInvertedMap() { Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap); int size = invColorMap.size(); Assertions.assertThat(invColorMap).hasSameSizeAs(colorMap).containsKeys(this.colorMap.values().toArray(new String[size])).containsValues(this.colorMap.keySet().toArray(new String[size])); } @Test(expected = IllegalArgumentException.class) public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() { Map<String, String> rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(new HashMap<String, String>(), this.color1DArray)); rgbMap.put("ORANGE", "#FFA500"); } @Test(expected = IllegalArgumentException.class) public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() { Map<String, String> uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate()); uniqValuesMap.put("NEW_RED", "#FF0000"); } @Test public void whenCreateLazyMap_theMapIsCreated() { Map<Integer, String> intStrMap = MapUtils.lazyMap(new HashMap<Integer, String>(), TransformerUtils.stringValueTransformer()); assertThat(intStrMap, is(anEmptyMap())); intStrMap.get(1); intStrMap.get(2); intStrMap.get(3); assertThat(intStrMap, is(aMapWithSize(3))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/circularfifoqueue/CircularFifoQueueUnitTest.java
libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/circularfifoqueue/CircularFifoQueueUnitTest.java
package com.baeldung.commons.collections.circularfifoqueue; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections4.queue.CircularFifoQueue; import org.junit.Assert; import org.junit.Test; public class CircularFifoQueueUnitTest { private static final int DEFAULT_SIZE = 32; private static final int FIXED_SIZE = 5; private static final int COLLECTION_SIZE = 7; private static final String TEST_COLOR = "Red"; private static final String TEST_COLOR_BY_INDEX = "Blue"; @Test public void whenUsingDefualtConstructor_correctSizeQueue() { CircularFifoQueue<String> bits = new CircularFifoQueue<>(); Assert.assertEquals(DEFAULT_SIZE, bits.maxSize()); } @Test public void givenAddElements_whenUsingIntConstructor_correctSizeQueue() { CircularFifoQueue<String> colors = new CircularFifoQueue<>(5); colors.add("Red"); colors.add("Blue"); colors.add("Green"); colors.offer("White"); colors.offer("Black"); Assert.assertEquals(FIXED_SIZE, colors.maxSize()); } @Test public void whenUsingCollectionConstructor_correctSizeQueue() { List<String> days = new ArrayList<>(); days.add("Monday"); days.add("Tuesday"); days.add("Wednesday"); days.add("Thursday"); days.add("Friday"); days.add("Saturday"); days.add("Sunday"); CircularFifoQueue<String> daysOfWeek = new CircularFifoQueue<>(days); Assert.assertEquals(COLLECTION_SIZE, daysOfWeek.maxSize()); } @Test public void givenAddElements_whenGetElement_correctElement() { CircularFifoQueue<String> colors = new CircularFifoQueue<>(5); colors.add("Red"); colors.add("Blue"); colors.add("Green"); colors.offer("White"); colors.offer("Black"); Assert.assertEquals(TEST_COLOR_BY_INDEX, colors.get(1)); } @Test public void givenAddElements_whenPollElement_correctElement() { CircularFifoQueue<String> colors = new CircularFifoQueue<>(5); colors.add("Red"); colors.add("Blue"); colors.add("Green"); colors.offer("White"); colors.offer("Black"); Assert.assertEquals(TEST_COLOR, colors.poll()); } @Test public void givenAddElements_whenPeekQueue_correctElement() { CircularFifoQueue<String> colors = new CircularFifoQueue<>(5); colors.add("Red"); colors.add("Blue"); colors.add("Green"); colors.offer("White"); colors.offer("Black"); Assert.assertEquals(TEST_COLOR, colors.peek()); } @Test public void givenAddElements_whenElementQueue_correctElement() { CircularFifoQueue<String> colors = new CircularFifoQueue<>(5); colors.add("Red"); colors.add("Blue"); colors.add("Green"); colors.offer("White"); colors.offer("Black"); Assert.assertEquals(TEST_COLOR, colors.element()); } @Test public void givenAddElements_whenRemoveElement_correctElement() { CircularFifoQueue<String> colors = new CircularFifoQueue<>(5); colors.add("Red"); colors.add("Blue"); colors.add("Green"); colors.offer("White"); colors.offer("Black"); Assert.assertEquals(TEST_COLOR, colors.remove()); } @Test public void givenFullQueue_whenClearQueue_getIsEmpty() { CircularFifoQueue<String> colors = new CircularFifoQueue<>(5); colors.add("Red"); colors.add("Blue"); colors.add("Green"); colors.offer("White"); colors.offer("Black"); colors.clear(); Assert.assertEquals(true, colors.isEmpty()); } @Test public void givenFullQueue_whenCheckFull_getIsFull() { CircularFifoQueue<String> colors = new CircularFifoQueue<>(5); colors.add("Red"); colors.add("Blue"); colors.add("Green"); colors.offer("White"); colors.offer("Black"); Assert.assertEquals(false, colors.isFull()); } @Test public void givenFullQueue_whenAddMoreElements_getIsAtFullCapacity() { CircularFifoQueue<String> colors = new CircularFifoQueue<>(5); colors.add("Red"); colors.add("Blue"); colors.add("Green"); colors.offer("White"); colors.offer("Black"); colors.add("Orange"); colors.add("Violet"); colors.add("Pink"); Assert.assertEquals(true, colors.isAtFullCapacity()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/collectionutils/CollectionUtilsGuideUnitTest.java
libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/collectionutils/CollectionUtilsGuideUnitTest.java
package com.baeldung.commons.collections.collectionutils; import com.baeldung.commons.collections.collectionutils.Address; import com.baeldung.commons.collections.collectionutils.Customer; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.Transformer; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class CollectionUtilsGuideUnitTest { Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234"); Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567"); List<Customer> list1, list2, list3, linkedList1; @Before public void setup() { Customer customer2 = new Customer(2, "Fredrik", 234567l, "locality2", "city2", "2345"); Customer customer3 = new Customer(3, "Kyle", 345678l, "locality3", "city3", "3456"); Customer customer5 = new Customer(5, "Cat", 567890l, "locality5", "city5", "5678"); Customer customer6 = new Customer(6, "John", 678901l, "locality6", "city6", "6789"); list1 = Arrays.asList(customer1, customer2, customer3); list2 = Arrays.asList(customer4, customer5, customer6); list3 = Arrays.asList(customer1, customer2); linkedList1 = new LinkedList<>(list1); } @Test public void givenList_whenAddIgnoreNull_thenNoNullAdded() { CollectionUtils.addIgnoreNull(list1, null); assertFalse(list1.contains(null)); } @Test public void givenTwoSortedLists_whenCollated_thenSorted() { List<Customer> sortedList = CollectionUtils.collate(list1, list2); assertEquals(6, sortedList.size()); assertTrue(sortedList.get(0).getName().equals("Bob")); assertTrue(sortedList.get(2).getName().equals("Daniel")); } @Test public void givenListOfCustomers_whenTransformed_thenListOfAddress() { Collection<Address> addressCol = CollectionUtils.collect(list1, new Transformer<Customer, Address>() { public Address transform(Customer customer) { return new Address(customer.getLocality(), customer.getCity(), customer.getZip()); } }); List<Address> addressList = new ArrayList<>(addressCol); assertTrue(addressList.size() == 3); assertTrue(addressList.get(0).getLocality().equals("locality1")); } @Test public void givenCustomerList_whenFiltered_thenCorrectSize() { boolean isModified = CollectionUtils.filter(linkedList1, new Predicate<Customer>() { public boolean evaluate(Customer customer) { return Arrays.asList("Daniel", "Kyle").contains(customer.getName()); } }); // filterInverse does the opposite. It removes the element from the list if the Predicate returns true // select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection assertTrue(isModified && linkedList1.size() == 2); } @Test public void givenNonEmptyList_whenCheckedIsNotEmpty_thenTrue() { List<Customer> emptyList = new ArrayList<>(); List<Customer> nullList = null; // Very handy at times where we want to check if a collection is not null and not empty too. // isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading assertTrue(CollectionUtils.isNotEmpty(list1)); assertTrue(CollectionUtils.isEmpty(nullList)); assertTrue(CollectionUtils.isEmpty(emptyList)); } @Test public void givenCustomerListAndASubcollection_whenChecked_thenTrue() { assertTrue(CollectionUtils.isSubCollection(list3, list1)); } @Test public void givenTwoLists_whenIntersected_thenCheckSize() { Collection<Customer> intersection = CollectionUtils.intersection(list1, list3); assertTrue(intersection.size() == 2); } @Test public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() { Collection<Customer> result = CollectionUtils.subtract(list1, list3); assertFalse(result.contains(customer1)); } @Test public void givenTwoLists_whenUnioned_thenCheckElementPresentInResult() { Collection<Customer> union = CollectionUtils.union(list1, list2); assertTrue(union.contains(customer1)); assertTrue(union.contains(customer4)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java
libraries-apache-commons-collections/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java
package com.baeldung.commons.collections.orderedmap; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.map.LinkedMap; import org.apache.commons.collections4.map.ListOrderedMap; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; public class OrderedMapUnitTest { private String[] names = { "Emily", "Mathew", "Rose", "John", "Anna" }; private Integer[] ages = { 37, 28, 40, 36, 21 }; private int RUNNERS_COUNT = names.length; private OrderedMap<String, Integer> runnersLinkedMap; private OrderedMap<String, Integer> runnersListOrderedMap; @Before public void createRunners() { // First implementation: ListOrderedMap this.runnersListOrderedMap = new ListOrderedMap<>(); this.loadOrderedMapOfRunners(this.runnersListOrderedMap); // Second implementation: LinkedMap this.runnersLinkedMap = new LinkedMap<>(); this.loadOrderedMapOfRunners(this.runnersLinkedMap); } private void loadOrderedMapOfRunners(OrderedMap<String, Integer> runners) { for (int i = 0; i < RUNNERS_COUNT; i++) { runners.put(this.names[i], this.ages[i]); } } @Test public void givenALinkedMap_whenIteratedWithMapIterator_thenPreservesOrder() { // Tests that the order in map iterator is the same // as defined in the constant arrays of names and ages: OrderedMapIterator<String, Integer> runnersIterator = this.runnersLinkedMap.mapIterator(); int i = 0; while (runnersIterator.hasNext()) { runnersIterator.next(); assertEquals(runnersIterator.getKey(), this.names[i]); assertEquals(runnersIterator.getValue(), this.ages[i]); i++; } } @Test public void givenAListOrderedMap_whenIteratedWithMapIterator_thenPreservesOrder() { // Tests that the order in map iterator is the same // as defined in the constant arrays of names and ages: OrderedMapIterator<String, Integer> runnersIterator = this.runnersListOrderedMap.mapIterator(); int i = 0; while (runnersIterator.hasNext()) { runnersIterator.next(); assertEquals(runnersIterator.getKey(), this.names[i]); assertEquals(runnersIterator.getValue(), this.ages[i]); i++; } } @Test public void givenALinkedMap_whenIteratedForwards_thenPreservesOrder() { // Tests that the order in the forward iteration is the same // as defined in the constant arrays of names and ages String name = this.runnersLinkedMap.firstKey(); int i = 0; while (name != null) { assertEquals(name, this.names[i]); name = this.runnersLinkedMap.nextKey(name); i++; } } @Test public void givenAListOrderedMap_whenIteratedForwards_thenPreservesOrder() { // Tests that the order in the forward iteration is the same // as defined in the constant arrays of names and ages String name = this.runnersListOrderedMap.firstKey(); int i = 0; while (name != null) { assertEquals(name, this.names[i]); name = this.runnersListOrderedMap.nextKey(name); i++; } } @Test public void givenALinkedMap_whenIteratedBackwards_thenPreservesOrder() { // Tests that the order in the backwards iteration is the same // as defined in the constant arrays of names and ages String name = this.runnersLinkedMap.lastKey(); int i = RUNNERS_COUNT - 1; while (name != null) { assertEquals(name, this.names[i]); name = this.runnersLinkedMap.previousKey(name); i--; } } @Test public void givenAListOrderedMap_whenIteratedBackwards_thenPreservesOrder() { // Tests that the order in the backwards iteration is the same // as defined in the constant arrays of names and ages String name = this.runnersListOrderedMap.lastKey(); int i = RUNNERS_COUNT - 1; while (name != null) { assertEquals(name, this.names[i]); name = this.runnersListOrderedMap.previousKey(name); i--; } } @Test public void givenALinkedMap_whenObjectIsSearched_thenMatchesConstantArray() { assertEquals(ages[4], this.runnersLinkedMap.get("Anna")); } @Test public void givenALinkedMap_whenConvertedToList_thenMatchesKeySet() { // Casting the OrderedMap to a LinkedMap we can use asList() method LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap; List<String> listKeys = new ArrayList<>(); listKeys.addAll(this.runnersLinkedMap.keySet()); List<String> linkedMap = lmap.asList(); assertEquals(listKeys, linkedMap); } @Test public void givenALinkedMap_whenSearchByIndexIsUsed_thenMatchesConstantArray() { LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap; for (int i = 0; i < RUNNERS_COUNT; i++) { // accessed by index: String name = lmap.get(i); assertEquals(name, this.names[i]); // index of key concides with position in array assertEquals(lmap.indexOf(this.names[i]), i); } } @Test public void givenALinkedMap_whenElementRemoved_thenSizeDecrease() { LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap; Integer johnAge = lmap.remove("John");// by object assertEquals(johnAge, Integer.valueOf(36)); assertEquals(lmap.size(), RUNNERS_COUNT - 1); Integer emilyAge = lmap.remove(0);// by index assertEquals(emilyAge, Integer.valueOf(37)); assertEquals(lmap.size(), RUNNERS_COUNT - 2); } @Test public void givenAListOrderedMap_whenObjectIsSearched_thenMatchesConstantArray() { assertEquals(ages[4], this.runnersListOrderedMap.get("Anna")); } @Test public void givenAListOrderedMap_whenConvertedToList_thenMatchesKeySet() { ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap; List<String> listKeys = new ArrayList<>(); listKeys.addAll(this.runnersListOrderedMap.keySet()); List<String> lomapList = lomap.asList(); assertEquals(listKeys, lomapList); } @Test public void givenAListOrderedMap_whenSearchByIndexIsUsed_thenMatchesConstantArray() { ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap; for (int i = 0; i < RUNNERS_COUNT; i++) { // accessed by index: String name = lomap.get(i); assertEquals(name, this.names[i]); // index of key concides with position in array assertEquals(lomap.indexOf(this.names[i]), i); } } @Test public void givenAListOrderedMap_whenElementRemoved_thenSizeDecrease() { ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap; Integer johnAge = lomap.remove("John");// by object assertEquals(johnAge, Integer.valueOf(36)); assertEquals(lomap.size(), RUNNERS_COUNT - 1); Integer emilyAge = lomap.remove(0);// by index assertEquals(emilyAge, Integer.valueOf(37)); assertEquals(lomap.size(), RUNNERS_COUNT - 2); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/test/java/com/baeldung/guava/GuavaUnitTest.java
libraries-apache-commons-collections/src/test/java/com/baeldung/guava/GuavaUnitTest.java
package com.baeldung.guava; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Test; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.BiMap; import com.google.common.collect.HashBasedTable; import com.google.common.collect.HashBiMap; import com.google.common.collect.Multimap; import com.google.common.collect.Table; public class GuavaUnitTest { private final static BiMap<Integer, String> daysOfWeek = HashBiMap.create(); private final static Multimap<String, String> groceryCart = ArrayListMultimap.create(); private final static Table<String, String, String> cityCoordinates = HashBasedTable.create(); private final static Table<String, String, String> movies = HashBasedTable.create(); private long start; static { daysOfWeek.put(1, "Monday"); daysOfWeek.put(2, "Tuesday"); daysOfWeek.put(3, "Wednesday"); daysOfWeek.put(4, "Thursday"); daysOfWeek.put(5, "Friday"); daysOfWeek.put(6, "Saturday"); daysOfWeek.put(7, "Sunday"); groceryCart.put("Fruits", "Apple"); groceryCart.put("Fruits", "Grapes"); groceryCart.put("Fruits", "Strawberries"); groceryCart.put("Vegetables", "Spinach"); groceryCart.put("Vegetables", "Cabbage"); cityCoordinates.put("40.7128° N", "74.0060° W", "New York"); cityCoordinates.put("48.8566° N", "2.3522° E", "Paris"); cityCoordinates.put("19.0760° N", "72.8777° E", "Mumbai"); movies.put("Tom Hanks", "Meg Ryan", "You've Got Mail"); movies.put("Tom Hanks", "Catherine Zeta-Jones", "The Terminal"); movies.put("Bradley Cooper", "Lady Gaga", "A Star is Born"); movies.put("Keenu Reaves", "Sandra Bullock", "Speed"); movies.put("Tom Hanks", "Sandra Bullock", "Extremely Loud & Incredibly Close"); } @Test public void givenBiMap_whenValue_thenKeyReturned() { assertEquals(Integer.valueOf(7), daysOfWeek.inverse() .get("Sunday")); } @Test public void givenBiMap_whenKey_thenValueReturned() { assertEquals("Tuesday", daysOfWeek.get(2)); } @Test public void givenMultiValuedMap_whenFruitsFetched_thenFruitsReturned() { List<String> fruits = Arrays.asList("Apple", "Grapes", "Strawberries"); assertEquals(fruits, groceryCart.get("Fruits")); } @Test public void givenMultiValuedMap_whenVeggiesFetched_thenVeggiesReturned() { List<String> veggies = Arrays.asList("Spinach", "Cabbage"); assertEquals(veggies, groceryCart.get("Vegetables")); } @Test public void givenMultiValuedMap_whenFuitsRemoved_thenVeggiesPreserved() { assertEquals(5, groceryCart.size()); groceryCart.remove("Fruits", "Apple"); assertEquals(4, groceryCart.size()); groceryCart.removeAll("Fruits"); assertEquals(2, groceryCart.size()); } @Test public void givenCoordinatesTable_whenFetched_thenOK() { List<String> expectedLongitudes = Arrays.asList("74.0060° W", "2.3522° E", "72.8777° E"); assertArrayEquals(expectedLongitudes.toArray(), cityCoordinates.columnKeySet() .toArray()); List<String> expectedCities = Arrays.asList("New York", "Paris", "Mumbai"); assertArrayEquals(expectedCities.toArray(), cityCoordinates.values() .toArray()); assertTrue(cityCoordinates.rowKeySet() .contains("48.8566° N")); } @Test public void givenMoviesTable_whenFetched_thenOK() { assertEquals(3, movies.row("Tom Hanks") .size()); assertEquals(2, movies.column("Sandra Bullock") .size()); assertEquals("A Star is Born", movies.get("Bradley Cooper", "Lady Gaga")); assertTrue(movies.containsValue("Speed")); } @Test public void givenHashBiMap_whenHundredThousandKeys_thenPerformanceNoted() { BiMap<Integer, Integer> map = HashBiMap.create(); start = System.nanoTime(); for (int i = 0; i < 100000; i++) { Integer key = Integer.valueOf(i); Integer value = Integer.valueOf(i + 1); map.put(key, value); } System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); start = System.nanoTime(); Integer value = map.get(Integer.valueOf(500)); System.out.println("Value:" + value); System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); start = System.nanoTime(); Integer key = map.inverse() .get(Integer.valueOf(501)); System.out.println("Key:" + key); System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/test/java/com/baeldung/apache/commons/CollectionsUnitTest.java
libraries-apache-commons-collections/src/test/java/com/baeldung/apache/commons/CollectionsUnitTest.java
package com.baeldung.apache.commons; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.MultiValuedMap; import org.apache.commons.collections4.bidimap.DualHashBidiMap; import org.apache.commons.collections4.bidimap.DualTreeBidiMap; import org.apache.commons.collections4.bidimap.TreeBidiMap; import org.apache.commons.collections4.map.MultiKeyMap; import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; import org.junit.Test; public class CollectionsUnitTest { private final static BidiMap<Integer, String> daysOfWeek = new TreeBidiMap<Integer, String>(); private final static MultiValuedMap<String, String> groceryCart = new ArrayListValuedHashMap<>(); private final static MultiKeyMap<String, String> days = new MultiKeyMap<String, String>(); private final static MultiKeyMap<String, String> cityCoordinates = new MultiKeyMap<String, String>(); private long start; static { daysOfWeek.put(1, "Monday"); daysOfWeek.put(2, "Tuesday"); daysOfWeek.put(3, "Wednesday"); daysOfWeek.put(4, "Thursday"); daysOfWeek.put(5, "Friday"); daysOfWeek.put(6, "Saturday"); daysOfWeek.put(7, "Sunday"); groceryCart.put("Fruits", "Apple"); groceryCart.put("Fruits", "Grapes"); groceryCart.put("Fruits", "Strawberries"); groceryCart.put("Vegetables", "Spinach"); groceryCart.put("Vegetables", "Cabbage"); days.put("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Weekday"); days.put("Saturday", "Sunday", "Weekend"); cityCoordinates.put("40.7128° N", "74.0060° W", "New York"); cityCoordinates.put("48.8566° N", "2.3522° E", "Paris"); cityCoordinates.put("19.0760° N", "72.8777° E", "Mumbai"); } @Test public void givenBidiMap_whenValue_thenKeyReturned() { assertEquals(Integer.valueOf(7), daysOfWeek.inverseBidiMap() .get("Sunday")); } @Test public void givenBidiMap_whenKey_thenValueReturned() { assertEquals("Tuesday", daysOfWeek.get(2)); } @Test public void givenMultiValuedMap_whenFruitsFetched_thenFruitsReturned() { List<String> fruits = Arrays.asList("Apple", "Grapes", "Strawberries"); assertEquals(fruits, groceryCart.get("Fruits")); } @Test public void givenMultiValuedMap_whenVeggiesFetched_thenVeggiesReturned() { List<String> veggies = Arrays.asList("Spinach", "Cabbage"); assertEquals(veggies, groceryCart.get("Vegetables")); } @Test public void givenMultiValuedMap_whenFuitsRemoved_thenVeggiesPreserved() { assertEquals(5, groceryCart.size()); groceryCart.remove("Fruits"); assertEquals(2, groceryCart.size()); } @Test public void givenDaysMultiKeyMap_whenFetched_thenOK() { assertFalse(days.get("Saturday", "Sunday") .equals("Weekday")); } @Test public void givenCoordinatesMultiKeyMap_whenQueried_thenOK() { List<String> expectedLongitudes = Arrays.asList("72.8777° E", "2.3522° E", "74.0060° W"); List<String> longitudes = new ArrayList<>(); cityCoordinates.forEach((key, value) -> { longitudes.add(key.getKey(1)); }); assertArrayEquals(expectedLongitudes.toArray(), longitudes.toArray()); List<String> expectedCities = Arrays.asList("Mumbai", "Paris", "New York"); List<String> cities = new ArrayList<>(); cityCoordinates.forEach((key, value) -> { cities.add(value); }); assertArrayEquals(expectedCities.toArray(), cities.toArray()); } @Test public void givenTreeBidiMap_whenHundredThousandKeys_thenPerformanceNoted() { System.out.println("**TreeBidiMap**"); BidiMap<Integer, Integer> map = new TreeBidiMap<>(); start = System.nanoTime(); for (int i = 0; i < 100000; i++) { Integer key = Integer.valueOf(i); Integer value = Integer.valueOf(i + 1); map.put(key, value); } System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); start = System.nanoTime(); Integer value = (Integer) map.get(Integer.valueOf(500)); System.out.println("Value:" + value); System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); start = System.nanoTime(); Integer key = (Integer) map.getKey(Integer.valueOf(501)); System.out.println("Key:" + key); System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); } @Test public void givenDualTreeBidiMap_whenHundredThousandKeys_thenPerformanceNoted() { System.out.println("**DualTreeBidiMap**"); BidiMap<Integer, Integer> map = new DualTreeBidiMap<>(); start = System.nanoTime(); for (int i = 0; i < 100000; i++) { Integer key = Integer.valueOf(i); Integer value = Integer.valueOf(i + 1); map.put(key, value); } System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); start = System.nanoTime(); Integer value = (Integer) map.get(Integer.valueOf(500)); System.out.println("Value:" + value); System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); start = System.nanoTime(); Integer key = (Integer) map.getKey(Integer.valueOf(501)); System.out.println("Key:" + key); System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); } @Test public void givenDualHashBidiMap_whenHundredThousandKeys_thenPerformanceNoted() { System.out.println("**DualHashBidiMap**"); BidiMap<Integer, Integer> map = new DualHashBidiMap<>(); start = System.nanoTime(); for (int i = 0; i < 100000; i++) { Integer key = Integer.valueOf(i); Integer value = Integer.valueOf(i + 1); map.put(key, value); } System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); start = System.nanoTime(); Integer value = (Integer) map.get(Integer.valueOf(500)); System.out.println("Value:" + value); System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); start = System.nanoTime(); Integer key = (Integer) map.getKey(Integer.valueOf(501)); System.out.println("Key:" + key); System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/main/java/com/baeldung/commons/collections/collectionutils/Address.java
libraries-apache-commons-collections/src/main/java/com/baeldung/commons/collections/collectionutils/Address.java
package com.baeldung.commons.collections.collectionutils; public class Address { private String locality; private String city; private String zip; public String getLocality() { return locality; } public void setLocality(String locality) { this.locality = locality; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Address [locality=").append(locality).append(", city=").append(city).append(", zip=").append(zip).append("]"); return builder.toString(); } public Address(String locality, String city, String zip) { super(); this.locality = locality; this.city = city; this.zip = zip; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-collections/src/main/java/com/baeldung/commons/collections/collectionutils/Customer.java
libraries-apache-commons-collections/src/main/java/com/baeldung/commons/collections/collectionutils/Customer.java
package com.baeldung.commons.collections.collectionutils; public class Customer implements Comparable<Customer> { private Integer id; private String name; private Long phone; private String locality; private String city; private String zip; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getPhone() { return phone; } public void setPhone(Long phone) { this.phone = phone; } public String getLocality() { return locality; } public void setLocality(String locality) { this.locality = locality; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public Customer(Integer id, String name, Long phone, String locality, String city, String zip) { super(); this.id = id; this.name = name; this.phone = phone; this.locality = locality; this.city = city; this.zip = zip; } public Customer(Integer id, String name, Long phone) { super(); this.id = id; this.name = name; this.phone = phone; } public Customer(String name) { super(); this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Customer other = (Customer) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public int compareTo(Customer o) { return this.name.compareTo(o.getName()); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Customer [id=").append(id).append(", name=").append(name).append(", phone=").append(phone).append("]"); return builder.toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/importannotation/zoo/ZooApplicationUnitTest.java
spring-di-3/src/test/java/com/baeldung/importannotation/zoo/ZooApplicationUnitTest.java
package com.baeldung.importannotation.zoo; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = ZooApplication.class) class ZooApplicationUnitTest { @Autowired ApplicationContext context; @Test void givenTheScanInTheAnimalPackage_whenGettingAnyAnimal_shallFindItInTheContext() { assertNotNull(context.getBean("dog")); assertNotNull(context.getBean("bird")); assertNotNull(context.getBean("cat")); assertNotNull(context.getBean("bug")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/importannotation/animal/AnimalConfigUnitTest.java
spring-di-3/src/test/java/com/baeldung/importannotation/animal/AnimalConfigUnitTest.java
package com.baeldung.importannotation.animal; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { AnimalConfiguration.class }) class AnimalConfigUnitTest { @Autowired ApplicationContext context; @Test void givenImportedBeans_whenGettingEach_shallFindOnlyTheImportedBeans() { assertThatBeanExists("dog", Dog.class); assertThatBeanExists("cat", Cat.class); assertThatBeanExists("bird", Cat.class); } private void assertThatBeanExists(String beanName, Class<?> beanClass) { assertTrue(context.containsBean(beanName)); assertNotNull(context.getBean(beanClass)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/importannotation/animal/ConfigUnitTest.java
spring-di-3/src/test/java/com/baeldung/importannotation/animal/ConfigUnitTest.java
package com.baeldung.importannotation.animal; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { BirdConfig.class, CatConfig.class, DogConfig.class }) class ConfigUnitTest { @Autowired ApplicationContext context; @Test void givenImportedBeans_whenGettingEach_shallFindIt() { assertThatBeanExists("dog", Dog.class); assertThatBeanExists("cat", Cat.class); assertThatBeanExists("bird", Bird.class); } private void assertThatBeanExists(String beanName, Class<?> beanClass) { assertTrue(context.containsBean(beanName)); assertNotNull(context.getBean(beanClass)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/importannotation/animal/MammalConfigUnitTest.java
spring-di-3/src/test/java/com/baeldung/importannotation/animal/MammalConfigUnitTest.java
package com.baeldung.importannotation.animal; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { MammalConfiguration.class }) class MammalConfigUnitTest { @Autowired ApplicationContext context; @Test void givenImportedBeans_whenGettingEach_shallFindOnlyTheImportedBeans() { assertThatBeanExists("dog", Dog.class); assertThatBeanExists("cat", Cat.class); assertFalse(context.containsBean("bird")); } private void assertThatBeanExists(String beanName, Class<?> beanClass) { assertTrue(context.containsBean(beanName)); assertNotNull(context.getBean(beanClass)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/importannotation/animal/BugConfigUnitTest.java
spring-di-3/src/test/java/com/baeldung/importannotation/animal/BugConfigUnitTest.java
package com.baeldung.importannotation.animal; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = BugConfig.class) class BugConfigUnitTest { @Autowired ApplicationContext context; @Test void givenImportInComponent_whenLookForBean_shallFindIt() { assertTrue(context.containsBean("bug")); assertNotNull(context.getBean(Bug.class)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java
spring-di-3/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java
package com.baeldung.dynamic.autowire; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = DynamicAutowireConfig.class) public class DynamicAutowireIntegrationTest { @Autowired private BeanFactoryDynamicAutowireService beanFactoryDynamicAutowireService; @Autowired private CustomMapFromListDynamicAutowireService customMapFromListDynamicAutowireService; @Test public void givenDynamicallyAutowiredBean_whenCheckingServerInGB_thenServerIsNotActive() { assertThat(beanFactoryDynamicAutowireService.isServerActive("GB", 101), is(false)); assertThat(customMapFromListDynamicAutowireService.isServerActive("GB", 101), is(false)); } @Test public void givenDynamicallyAutowiredBean_whenCheckingServerInUS_thenServerIsActive() { assertThat(beanFactoryDynamicAutowireService.isServerActive("US", 101), is(true)); assertThat(customMapFromListDynamicAutowireService.isServerActive("US", 101), is(true)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java
spring-di-3/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java
package com.baeldung.methodinjections; import org.junit.Test; import org.junit.jupiter.api.AfterEach; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class StudentIntegrationTest { private ConfigurableApplicationContext context; @AfterEach public void tearDown() { context.close(); } @Test public void whenLookupMethodCalled_thenNewInstanceReturned() { context = new AnnotationConfigApplicationContext(AppConfig.class); Student student1 = context.getBean("studentBean", Student.class); Student student2 = context.getBean("studentBean", Student.class); assertEquals(student1, student2); assertNotEquals(student1.getNotification("Alex"), student2.getNotification("Bethany")); } @Test public void whenAbstractGetterMethodInjects_thenNewInstanceReturned() { context = new ClassPathXmlApplicationContext("beans.xml"); StudentServices services = context.getBean("studentServices", StudentServices.class); assertEquals("PASS", services.appendMark("Alex", 76)); assertEquals("FAIL", services.appendMark("Bethany", 44)); assertEquals("PASS", services.appendMark("Claire", 96)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
spring-di-3/src/test/java/com/baeldung/autowiring/controller/CorrectControllerIntegrationTest.java
package com.baeldung.autowiring.controller; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @ExtendWith(SpringExtension.class) @SpringBootTest public class CorrectControllerIntegrationTest { @Autowired CorrectController controller; @Test void whenControl_ThenRunSuccessfully() { assertDoesNotThrow(() -> controller.control()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
spring-di-3/src/test/java/com/baeldung/autowiring/controller/FlawedControllerIntegrationTest.java
package com.baeldung.autowiring.controller; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertThrows; @ExtendWith(SpringExtension.class) @SpringBootTest public class FlawedControllerIntegrationTest { private static final Logger LOGGER = LoggerFactory.getLogger(FlawedControllerIntegrationTest.class); @Autowired FlawedController myController; @Test void whenControl_ThenThrowNullPointerException() { NullPointerException npe = assertThrows(NullPointerException.class, () -> myController.control()); LOGGER.error("Got a NullPointerException", npe); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/countingbeans/latestsspring/AnnotatedBeansIntegrationTest.java
spring-di-3/src/test/java/com/baeldung/countingbeans/latestsspring/AnnotatedBeansIntegrationTest.java
package com.baeldung.countingbeans.latestsspring; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class AnnotatedBeansIntegrationTest { /** * Note : this test fails with any spring version < 2.2 * Before, the getBeansWithAnnotation method was not checking the beans created via factory method * Please find the change here : https://github.com/spring-projects/spring-framework/commit/e0fe32af05ac525ef5e11c3ac5195a08759bb85e */ @Test void whenApplicationContextStarted_ThenShouldDetectAllAnnotatedBeans() { try (AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext( MyComponent.class, MyConfigurationBean.class )) { Map<String,Object> beans = applicationContext.getBeansWithAnnotation(MyCustomAnnotation.class); assertEquals(2, beans.size()); assertTrue(beans.keySet().containsAll(Arrays.asList("myComponent", "myService"))); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/countingbeans/olderspring/factorybeans/AnnotatedBeansIntegrationTest.java
spring-di-3/src/test/java/com/baeldung/countingbeans/olderspring/factorybeans/AnnotatedBeansIntegrationTest.java
package com.baeldung.countingbeans.olderspring.factorybeans; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {MyConfigurationBean.class, AnnotatedBeansComponent.class}) public class AnnotatedBeansIntegrationTest { @Autowired AnnotatedBeansComponent annotatedBeansComponent; @Test void whenBeanUtilsGetBeansWithAnnotation_ThenShouldListAnnotatedBean() { try (AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfigurationBean.class)) { List<String> result = BeanUtils.getBeansWithAnnotation(applicationContext, MyCustomAnnotation.class); assertEquals(1, result.size()); assertEquals("myService", result.get(0)); } } @Test void whenBeanUtilsGetBeansWithAnnotationStreamVersion_ThenShouldListAnnotatedBean() { try (AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfigurationBean.class)) { List<String> result = BeanUtils.getBeansWithAnnotation(applicationContext, MyCustomAnnotation.class); assertEquals(1, result.size()); assertEquals("myService", result.get(0)); } } @Test void whenAnnotatedBeansComponentGetBeansWithAnnotation_ThenShouldListAnnotatedBean() { List<String> result = annotatedBeansComponent.getBeansWithAnnotation(MyCustomAnnotation.class); assertEquals(1, result.size()); assertEquals("myService", result.get(0)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/test/java/com/baeldung/countingbeans/olderspring/qualifier/AnnotatedBeansIntegrationTest.java
spring-di-3/src/test/java/com/baeldung/countingbeans/olderspring/qualifier/AnnotatedBeansIntegrationTest.java
package com.baeldung.countingbeans.olderspring.qualifier; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = {MyComponent.class, MyConfigurationBean.class}) public class AnnotatedBeansIntegrationTest { @Autowired @MyCustomAnnotation private List<Object> annotatedBeans; @Test void whenAutowiring_ThenShouldDetectAllAnnotatedBeans() { assertEquals(2, annotatedBeans.size()); List<String> classNames = annotatedBeans.stream() .map(Object::getClass) .map(Class::getName) .map(s -> s.substring(s.lastIndexOf(".") + 1)) .collect(Collectors.toList()); assertTrue(classNames.containsAll(Arrays.asList("MyComponent", "MyService"))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/zoo/ZooApplication.java
spring-di-3/src/main/java/com/baeldung/importannotation/zoo/ZooApplication.java
package com.baeldung.importannotation.zoo; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import com.baeldung.importannotation.animal.AnimalScanConfiguration; @Configuration @Import(AnimalScanConfiguration.class) class ZooApplication { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/Dog.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/Dog.java
package com.baeldung.importannotation.animal; class Dog { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/CatConfig.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/CatConfig.java
package com.baeldung.importannotation.animal; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration class CatConfig { @Bean Cat cat() { return new Cat(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/Cat.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/Cat.java
package com.baeldung.importannotation.animal; class Cat { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/Bug.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/Bug.java
package com.baeldung.importannotation.animal; import org.springframework.stereotype.Component; @Component(value = "bug") class Bug { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/AnimalConfiguration.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/AnimalConfiguration.java
package com.baeldung.importannotation.animal; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({ MammalConfiguration.class, BirdConfig.class }) class AnimalConfiguration { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/Bird.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/Bird.java
package com.baeldung.importannotation.animal; class Bird { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/BirdConfig.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/BirdConfig.java
package com.baeldung.importannotation.animal; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration class BirdConfig { @Bean Bird bird() { return new Bird(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/MammalConfiguration.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/MammalConfiguration.java
package com.baeldung.importannotation.animal; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({ DogConfig.class, CatConfig.class }) class MammalConfiguration { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/DogConfig.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/DogConfig.java
package com.baeldung.importannotation.animal; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration class DogConfig { @Bean Dog dog() { return new Dog(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/AnimalScanConfiguration.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/AnimalScanConfiguration.java
package com.baeldung.importannotation.animal; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan public class AnimalScanConfiguration { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/importannotation/animal/BugConfig.java
spring-di-3/src/main/java/com/baeldung/importannotation/animal/BugConfig.java
package com.baeldung.importannotation.animal; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import(Bug.class) class BugConfig { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/dynamic/autowire/DynamicAutowireConfig.java
spring-di-3/src/main/java/com/baeldung/dynamic/autowire/DynamicAutowireConfig.java
package com.baeldung.dynamic.autowire; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.baeldung.dynamic.autowire") public class DynamicAutowireConfig { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/dynamic/autowire/RegionService.java
spring-di-3/src/main/java/com/baeldung/dynamic/autowire/RegionService.java
package com.baeldung.dynamic.autowire; public interface RegionService { boolean isServerActive(int serverId); String getISOCountryCode(); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java
spring-di-3/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java
package com.baeldung.dynamic.autowire; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BeanFactoryDynamicAutowireService { private static final String SERVICE_NAME_SUFFIX = "regionService"; private final BeanFactory beanFactory; @Autowired public BeanFactoryDynamicAutowireService(BeanFactory beanFactory) { this.beanFactory = beanFactory; } public boolean isServerActive(String isoCountryCode, int serverId) { RegionService service = beanFactory.getBean(getRegionServiceBeanName(isoCountryCode), RegionService.class); return service.isServerActive(serverId); } private String getRegionServiceBeanName(String isoCountryCode) { return isoCountryCode + SERVICE_NAME_SUFFIX; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/dynamic/autowire/USRegionService.java
spring-di-3/src/main/java/com/baeldung/dynamic/autowire/USRegionService.java
package com.baeldung.dynamic.autowire; import org.springframework.stereotype.Service; @Service("USregionService") public class USRegionService implements RegionService { @Override public boolean isServerActive(int serverId) { return true; } @Override public String getISOCountryCode() { return "US"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/dynamic/autowire/GBRegionService.java
spring-di-3/src/main/java/com/baeldung/dynamic/autowire/GBRegionService.java
package com.baeldung.dynamic.autowire; import org.springframework.stereotype.Service; @Service("GBregionService") public class GBRegionService implements RegionService { @Override public boolean isServerActive(int serverId) { return false; } @Override public String getISOCountryCode() { return "GB"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/dynamic/autowire/CustomMapFromListDynamicAutowireService.java
spring-di-3/src/main/java/com/baeldung/dynamic/autowire/CustomMapFromListDynamicAutowireService.java
package com.baeldung.dynamic.autowire; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; @Service public class CustomMapFromListDynamicAutowireService { private final Map<String, RegionService> servicesByCountryCode; @Autowired public CustomMapFromListDynamicAutowireService(List<RegionService> regionServices) { servicesByCountryCode = regionServices.stream() .collect(Collectors.toMap(RegionService::getISOCountryCode, Function.identity())); } public boolean isServerActive(String isoCountryCode, int serverId) { RegionService service = servicesByCountryCode.get(isoCountryCode); return service.isServerActive(serverId); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/methodinjections/StudentServices.java
spring-di-3/src/main/java/com/baeldung/methodinjections/StudentServices.java
package com.baeldung.methodinjections; import org.springframework.beans.factory.annotation.Lookup; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Component("studentService") public abstract class StudentServices { private final Map<String, SchoolNotification> notes = new HashMap<>(); @Lookup protected abstract SchoolNotification getNotification(String name); public String appendMark(String name, Integer mark) { SchoolNotification notification = notes.computeIfAbsent(name, exists -> getNotification(name)); return notification.addMark(mark); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/methodinjections/Student.java
spring-di-3/src/main/java/com/baeldung/methodinjections/Student.java
package com.baeldung.methodinjections; import org.springframework.beans.factory.annotation.Lookup; import org.springframework.stereotype.Component; @Component("studentBean") public class Student { private String id; /** * Injects a prototype bean SchoolNotification into Singleton student */ @Lookup public SchoolNotification getNotification(String name) { // spring overrides and returns a SchoolNotification instance return null; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/methodinjections/AppConfig.java
spring-di-3/src/main/java/com/baeldung/methodinjections/AppConfig.java
package com.baeldung.methodinjections; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages = "com.baeldung.methodinjections") public class AppConfig { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/methodinjections/SchoolNotification.java
spring-di-3/src/main/java/com/baeldung/methodinjections/SchoolNotification.java
package com.baeldung.methodinjections; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Collection; @Component("schoolNotification") @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class SchoolNotification { @Autowired Grader grader; private String name; private Collection<Integer> marks; public SchoolNotification(String name) { this.name = name; this.marks = new ArrayList<>(); } public String addMark(Integer mark) { this.marks.add(mark); return this.grader.grade(this.marks); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection<Integer> getMarks() { return marks; } public void setMarks(Collection<Integer> marks) { this.marks = marks; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/methodinjections/Grader.java
spring-di-3/src/main/java/com/baeldung/methodinjections/Grader.java
package com.baeldung.methodinjections; import org.springframework.stereotype.Component; import java.util.Collection; @Component public class Grader { public String grade(Collection<Integer> marks) { boolean result = marks.stream() .anyMatch(mark -> mark < 45); if (result) { return "FAIL"; } return "PASS"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/autowiring/App.java
spring-di-3/src/main/java/com/baeldung/autowiring/App.java
package com.baeldung.autowiring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
spring-di-3/src/main/java/com/baeldung/autowiring/controller/CorrectController.java
package com.baeldung.autowiring.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.baeldung.autowiring.service.MyService; @Controller public class CorrectController { @Autowired MyService myService; public String control() { return myService.serve(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
spring-di-3/src/main/java/com/baeldung/autowiring/controller/FlawedController.java
package com.baeldung.autowiring.controller; import org.springframework.stereotype.Controller; import com.baeldung.autowiring.service.MyService; @Controller public class FlawedController { public String control() { MyService userService = new MyService(); return userService.serve(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
spring-di-3/src/main/java/com/baeldung/autowiring/service/MyServiceConfiguration.java
package com.baeldung.autowiring.service; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyServiceConfiguration { @Bean MyService myService() { return new MyService(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyService.java
spring-di-3/src/main/java/com/baeldung/autowiring/service/MyService.java
package com.baeldung.autowiring.service; import org.springframework.beans.factory.annotation.Autowired; /** * The bean corresponding to this class is defined in MyServiceConfiguration * Alternatively, you could choose to decorate this class with @Component or @Service */ public class MyService { @Autowired MyComponent myComponent; public String serve() { myComponent.doWork(); return "success"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/autowiring/service/MyComponent.java
spring-di-3/src/main/java/com/baeldung/autowiring/service/MyComponent.java
package com.baeldung.autowiring.service; import org.springframework.stereotype.Component; @Component public class MyComponent { public void doWork() {} }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/latestsspring/MyService.java
spring-di-3/src/main/java/com/baeldung/countingbeans/latestsspring/MyService.java
package com.baeldung.countingbeans.latestsspring; public class MyService { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/latestsspring/MyCustomAnnotation.java
spring-di-3/src/main/java/com/baeldung/countingbeans/latestsspring/MyCustomAnnotation.java
package com.baeldung.countingbeans.latestsspring; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention( RetentionPolicy.RUNTIME ) public @interface MyCustomAnnotation { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/latestsspring/MyComponent.java
spring-di-3/src/main/java/com/baeldung/countingbeans/latestsspring/MyComponent.java
package com.baeldung.countingbeans.latestsspring; import org.springframework.stereotype.Component; @Component @MyCustomAnnotation public class MyComponent { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/latestsspring/MyConfigurationBean.java
spring-di-3/src/main/java/com/baeldung/countingbeans/latestsspring/MyConfigurationBean.java
package com.baeldung.countingbeans.latestsspring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyConfigurationBean { @Bean @MyCustomAnnotation MyService myService() { return new MyService(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/factorybeans/MyService.java
spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/factorybeans/MyService.java
package com.baeldung.countingbeans.olderspring.factorybeans; public class MyService { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/factorybeans/MyCustomAnnotation.java
spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/factorybeans/MyCustomAnnotation.java
package com.baeldung.countingbeans.olderspring.factorybeans; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention( RetentionPolicy.RUNTIME ) public @interface MyCustomAnnotation { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/factorybeans/AnnotatedBeansComponent.java
spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/factorybeans/AnnotatedBeansComponent.java
package com.baeldung.countingbeans.olderspring.factorybeans; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.GenericApplicationContext; import org.springframework.stereotype.Component; @Component public class AnnotatedBeansComponent { @Autowired GenericApplicationContext applicationContext; public List<String> getBeansWithAnnotation(Class<?> annotationClass) { return BeanUtils.getBeansWithAnnotation(applicationContext, annotationClass); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/factorybeans/MyConfigurationBean.java
spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/factorybeans/MyConfigurationBean.java
package com.baeldung.countingbeans.olderspring.factorybeans; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyConfigurationBean { @Bean @MyCustomAnnotation MyService myService() { return new MyService(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/factorybeans/BeanUtils.java
spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/factorybeans/BeanUtils.java
package com.baeldung.countingbeans.olderspring.factorybeans; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class BeanUtils { // NB : this method lists only beans created via factory methods public static List<String> getBeansWithAnnotation(GenericApplicationContext applicationContext, Class<?> annotationClass) { List<String> result = new ArrayList<String>(); ConfigurableListableBeanFactory factory = applicationContext.getBeanFactory(); for(String name : factory.getBeanDefinitionNames()) { BeanDefinition bd = factory.getBeanDefinition(name); if(bd.getSource() instanceof AnnotatedTypeMetadata) { AnnotatedTypeMetadata metadata = (AnnotatedTypeMetadata) bd.getSource(); if (metadata.getAnnotationAttributes(annotationClass.getName()) != null) { result.add(name); } } } return result; } // NB : list beans created via factory methods using streams (same method as before, written differently) public static List<String> getBeansWithAnnotation_StreamVersion(GenericApplicationContext applicationContext, Class<?> annotationClass) { ConfigurableListableBeanFactory factory = applicationContext.getBeanFactory(); return Arrays.stream(factory.getBeanDefinitionNames()) .filter(name -> isAnnotated(factory, name, annotationClass)) .collect(Collectors.toList()); } private static boolean isAnnotated(ConfigurableListableBeanFactory factory, String beanName, Class<?> clazz) { BeanDefinition beanDefinition = factory.getBeanDefinition(beanName); if(beanDefinition.getSource() instanceof AnnotatedTypeMetadata) { AnnotatedTypeMetadata metadata = (AnnotatedTypeMetadata) beanDefinition.getSource(); return metadata.getAnnotationAttributes(clazz.getName()) != null; } return false; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/qualifier/MyService.java
spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/qualifier/MyService.java
package com.baeldung.countingbeans.olderspring.qualifier; public class MyService { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/qualifier/MyCustomAnnotation.java
spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/qualifier/MyCustomAnnotation.java
package com.baeldung.countingbeans.olderspring.qualifier; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import org.springframework.beans.factory.annotation.Qualifier; @Retention( RetentionPolicy.RUNTIME ) @Qualifier public @interface MyCustomAnnotation { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/qualifier/MyComponent.java
spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/qualifier/MyComponent.java
package com.baeldung.countingbeans.olderspring.qualifier; import org.springframework.stereotype.Component; @Component @MyCustomAnnotation public class MyComponent { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/qualifier/MyConfigurationBean.java
spring-di-3/src/main/java/com/baeldung/countingbeans/olderspring/qualifier/MyConfigurationBean.java
package com.baeldung.countingbeans.olderspring.qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyConfigurationBean { @Bean @MyCustomAnnotation MyService myService() { return new MyService(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/test/java/com/baeldung/sbe/test/EncodeDecodeMarketDataUnitTest.java
libraries-3/src/test/java/com/baeldung/sbe/test/EncodeDecodeMarketDataUnitTest.java
package com.baeldung.sbe.test; import java.math.BigDecimal; import java.nio.ByteBuffer; import org.agrona.concurrent.UnsafeBuffer; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.baeldung.sbe.MarketData; import com.baeldung.sbe.stub.Currency; import com.baeldung.sbe.stub.Market; import com.baeldung.sbe.stub.MessageHeaderDecoder; import com.baeldung.sbe.stub.MessageHeaderEncoder; import com.baeldung.sbe.stub.TradeDataDecoder; import com.baeldung.sbe.stub.TradeDataEncoder; public class EncodeDecodeMarketDataUnitTest { private MarketData marketData; @BeforeEach public void setup() { marketData = new MarketData(2, 128.99, Market.NYSE, Currency.USD, "IBM"); } @Test public void givenMarketData_whenEncode_thenDecodedValuesMatch() { // our buffer to write encoded data, initial cap. 128 bytes UnsafeBuffer buffer = new UnsafeBuffer(ByteBuffer.allocate(128)); // necessary encoders MessageHeaderEncoder headerEncoder = new MessageHeaderEncoder(); TradeDataEncoder dataEncoder = new TradeDataEncoder(); // we parse price data (double) into two parts: mantis and exponent BigDecimal priceDecimal = BigDecimal.valueOf(marketData.getPrice()); int priceMantissa = priceDecimal.scaleByPowerOfTen(priceDecimal.scale()) .intValue(); int priceExponent = priceDecimal.scale() * -1; // encode data TradeDataEncoder encoder = dataEncoder.wrapAndApplyHeader(buffer, 0, headerEncoder); encoder.amount(marketData.getAmount()); encoder.quote() .market(marketData.getMarket()) .currency(marketData.getCurrency()) .symbol(marketData.getSymbol()) .price() .mantissa(priceMantissa) .exponent((byte) priceExponent); // necessary decoders MessageHeaderDecoder headerDecoder = new MessageHeaderDecoder(); TradeDataDecoder dataDecoder = new TradeDataDecoder(); // decode data dataDecoder.wrapAndApplyHeader(buffer, 0, headerDecoder); // decode price data (from mantissa and exponent) into a double double price = BigDecimal.valueOf(dataDecoder.quote() .price() .mantissa()) .scaleByPowerOfTen(dataDecoder.quote() .price() .exponent()) .doubleValue(); // ensure we have the exact same values Assertions.assertEquals(2, dataDecoder.amount()); Assertions.assertEquals("IBM", dataDecoder.quote() .symbol()); Assertions.assertEquals(Market.NYSE, dataDecoder.quote() .market()); Assertions.assertEquals(Currency.USD, dataDecoder.quote() .currency()); Assertions.assertEquals(128.99, price); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/test/java/com/baeldung/javers/JaversUnitTest.java
libraries-3/src/test/java/com/baeldung/javers/JaversUnitTest.java
package com.baeldung.javers; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.javers.common.collections.Lists; import org.javers.core.Javers; import org.javers.core.JaversBuilder; import org.javers.core.diff.Diff; import org.javers.core.diff.changetype.NewObject; import org.javers.core.diff.changetype.ObjectRemoved; import org.javers.core.diff.changetype.ValueChange; import org.javers.core.diff.changetype.container.ListChange; import org.junit.Test; public class JaversUnitTest { @Test public void givenPersonObject_whenApplyModificationOnIt_thenShouldDetectChange() { // given Javers javers = JaversBuilder.javers().build(); Person person = new Person(1, "Michael Program"); Person personAfterModification = new Person(1, "Michael Java"); // when Diff diff = javers.compare(person, personAfterModification); // then ValueChange change = diff.getChangesByType(ValueChange.class).get(0); assertThat(diff.getChanges()).hasSize(1); assertThat(change.getPropertyName()).isEqualTo("name"); assertThat(change.getLeft()).isEqualTo("Michael Program"); assertThat(change.getRight()).isEqualTo("Michael Java"); } @Test public void givenListOfPersons_whenCompare_ThenShouldDetectChanges() { // given Javers javers = JaversBuilder.javers().build(); Person personThatWillBeRemoved = new Person(2, "Thomas Link"); List<Person> oldList = Lists.asList(new Person(1, "Michael Program"), personThatWillBeRemoved); List<Person> newList = Lists.asList(new Person(1, "Michael Not Program")); // when Diff diff = javers.compareCollections(oldList, newList, Person.class); // then assertThat(diff.getChanges()).hasSize(3); ValueChange valueChange = diff.getChangesByType(ValueChange.class).get(0); assertThat(valueChange.getPropertyName()).isEqualTo("name"); assertThat(valueChange.getLeft()).isEqualTo("Michael Program"); assertThat(valueChange.getRight()).isEqualTo("Michael Not Program"); ObjectRemoved objectRemoved = diff.getChangesByType(ObjectRemoved.class).get(0); assertThat(objectRemoved.getAffectedObject().get().equals(personThatWillBeRemoved)).isTrue(); ListChange listChange = diff.getChangesByType(ListChange.class).get(0); assertThat(listChange.getValueRemovedChanges().size()).isEqualTo(1); } @Test public void givenListOfPerson_whenPersonHasNewAddress_thenDetectThatChange() { // given Javers javers = JaversBuilder.javers().build(); PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"), new Address("USA"))); // when Diff diff = javers.compare(person, personWithNewAddress); List objectsByChangeType = diff.getObjectsByChangeType(NewObject.class); // then assertThat(objectsByChangeType).hasSize(1); assertThat(objectsByChangeType.get(0).equals(new Address("USA"))); } @Test public void givenListOfPerson_whenPersonRemovedAddress_thenDetectThatChange() { // given Javers javers = JaversBuilder.javers().build(); PersonWithAddress person = new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England"))); PersonWithAddress personWithNewAddress = new PersonWithAddress(1, "Tom", Collections.emptyList()); // when Diff diff = javers.compare(person, personWithNewAddress); List objectsByChangeType = diff.getObjectsByChangeType(ObjectRemoved.class); // then assertThat(objectsByChangeType).hasSize(1); assertThat(objectsByChangeType.get(0).equals(new Address("England"))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/test/java/com/baeldung/failsafe/CircuitBreakerUnitTest.java
libraries-3/src/test/java/com/baeldung/failsafe/CircuitBreakerUnitTest.java
package com.baeldung.failsafe; import java.time.Duration; import org.junit.jupiter.api.Test; import dev.failsafe.CircuitBreaker; import dev.failsafe.Failsafe; import dev.failsafe.FailsafeExecutor; public class CircuitBreakerUnitTest { @Test void test() throws InterruptedException { CircuitBreaker<Object> circuitBreaker = CircuitBreaker.builder() .withFailureThreshold(5) .withDelay(Duration.ofMillis(400)) .withSuccessThreshold(4) .build(); FailsafeExecutor<Object> executor = Failsafe.with(circuitBreaker); for (int i = 0; i < 30; ++i) { int finalI = i; System.out.println("Calling " + finalI + " - " + circuitBreaker.getState()); try { executor.run(() -> { System.out.println("Called " + finalI + " - " + circuitBreaker.getState()); if (circuitBreaker.getState() == CircuitBreaker.State.CLOSED) { throw new Exception(); } }); } catch (Exception e) {} Thread.sleep(100); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/test/java/com/baeldung/failsafe/FallbackUnitTest.java
libraries-3/src/test/java/com/baeldung/failsafe/FallbackUnitTest.java
package com.baeldung.failsafe; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import org.junit.jupiter.api.Test; import dev.failsafe.Failsafe; import dev.failsafe.FailsafeExecutor; import dev.failsafe.Fallback; public class FallbackUnitTest { @Test void fallbackOnSuccessTest() { Fallback<Integer> policy = Fallback.builder(0) .build(); Integer result = Failsafe.with(policy).get(() -> 1); assertEquals(1, result); } @Test void fallbackOnExceptionTest() { Fallback<Integer> policy = Fallback.builder(0) .build(); Integer result = Failsafe.with(policy).get(() -> {throw new Exception();}); assertEquals(0, result); } @Test void fallbackOnConfiguredExceptionTest() { Fallback<Integer> defaultPolicy = Fallback.builder(0).build(); Fallback<Integer> npePolicy = Fallback.builder(1) .handle(NullPointerException.class) .build(); Fallback<Integer> ioePolicy = Fallback.builder(2) .handleIf(e -> e instanceof IOException) .build(); FailsafeExecutor<Integer> executor = Failsafe.with(defaultPolicy, npePolicy, ioePolicy); assertEquals(0, executor.get(() -> {throw new Exception();})); assertEquals(1, executor.get(() -> {throw new NullPointerException();})); assertEquals(2, executor.get(() -> {throw new IOException();})); } @Test void fallbackOnLambdaResultTest() { Fallback<Integer> policy = Fallback.builder(1) .handleResult(null) .handleResultIf(result -> result < 0) .build(); FailsafeExecutor<Integer> executor = Failsafe.with(policy); assertEquals(1, executor.get(() -> null)); assertEquals(1, executor.get(() -> -1)); assertEquals(2, executor.get(() -> 2)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false