BAEL-3091: The Prototype Pattern in Java (changed code based on valid comments from a reader)

This commit is contained in:
Vivek Balasubramaniam
2019-10-29 22:27:15 +05:30
parent db85c8f275
commit d3d5b060e7
20517 changed files with 1642290 additions and 0 deletions
@@ -0,0 +1,33 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.config.H2JpaConfig;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { Application.class, H2JpaConfig.class })
public class SpringBootH2IntegrationTest {
@Autowired
private GenericEntityRepository genericEntityRepository;
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}
}
@@ -0,0 +1,29 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringBootJPAIntegrationTest {
@Autowired
private GenericEntityRepository genericEntityRepository;
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}
}
@@ -0,0 +1,31 @@
package com.baeldung;
import com.baeldung.boot.Application;
import com.baeldung.boot.domain.GenericEntity;
import com.baeldung.boot.repository.GenericEntityRepository;
import com.baeldung.config.H2TestProfileJPAConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class, H2TestProfileJPAConfig.class })
@ActiveProfiles("test")
public class SpringBootProfileIntegrationTest {
@Autowired
private GenericEntityRepository genericEntityRepository;
@Test
public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test"));
GenericEntity foundEntity = genericEntityRepository.findById(genericEntity.getId()).orElse(null);
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}
}
@@ -0,0 +1,62 @@
package com.baeldung.boot.naming;
import org.assertj.core.api.SoftAssertions;
import org.hibernate.boot.Metadata;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Table;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.naming.NamingConfig.Config;
import com.baeldung.boot.naming.entity.Account;
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(properties = {
"spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl",
"spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl"
})
@Import(Config.class)
public class LegacyJpaImplNamingIntegrationTest extends NamingConfig {
@Test
public void givenLegacyJpaImplNamingStrategy_whenCreateDatabase_thenGetStrategyNames() {
Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
String entity = Account.class.getCanonicalName();
PersistentClass persistentClass = metadata.getEntityBinding(entity);
Table table = persistentClass.getTable();
String physicalNameExpected = "Secondary_Email";
String implicitNameExpected = "defaultEmail";
String tableNameExpected = "Account";
String tableNameCreated = table.getName();
boolean columnNameIsQuoted = table
.getColumn(3)
.isQuoted();
String physicalNameCreated = table
.getColumn(3)
.getName();
String implicitNameCreated = table
.getColumn(2)
.getName();
SoftAssertions.assertSoftly(softly -> {
softly
.assertThat(columnNameIsQuoted)
.isTrue();
softly
.assertThat(tableNameCreated)
.isEqualTo(tableNameExpected);
softly
.assertThat(physicalNameCreated)
.isEqualTo(physicalNameExpected);
softly
.assertThat(implicitNameCreated)
.isEqualTo(implicitNameExpected);
});
}
}
@@ -0,0 +1,15 @@
package com.baeldung.boot.naming;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
public class NamingConfig {
@TestConfiguration
static class Config {
@Bean
public HibernatePropertiesCustomizer customizer() {
return new HibernateConfig();
}
}
}
@@ -0,0 +1,56 @@
package com.baeldung.boot.naming;
import org.assertj.core.api.SoftAssertions;
import org.hibernate.boot.Metadata;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Table;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.naming.NamingConfig.Config;
import com.baeldung.boot.naming.entity.Account;
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(properties = {
"spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy",
"spring.jpa.hibernate.naming.implicit-strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
})
@Import(Config.class)
public class SpringBootDefaultNamingIntegrationTest extends NamingConfig {
@Test
public void givenDefaultBootNamingStrategy_whenCreateDatabase_thenGetStrategyNames() {
Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
String entity = Account.class.getCanonicalName();
PersistentClass persistentClass = metadata.getEntityBinding(entity);
Table table = persistentClass.getTable();
String physicalNameExpected = "secondary_email";
String implicitNameExpected = "default_email";
String tableNameExpected = "account";
String tableNameCreated = table.getName();
String physicalNameCreated = table
.getColumn(3)
.getName();
String implicitNameCreated = table
.getColumn(2)
.getName();
SoftAssertions softly = new SoftAssertions();
softly
.assertThat(tableNameCreated)
.isEqualTo(tableNameExpected);
softly
.assertThat(physicalNameCreated)
.isEqualTo(physicalNameExpected);
softly
.assertThat(implicitNameCreated)
.isEqualTo(implicitNameExpected);
softly.assertAll();
}
}
@@ -0,0 +1,63 @@
package com.baeldung.boot.naming;
import com.baeldung.boot.naming.MetadataExtractorIntegrator;
import com.baeldung.boot.naming.NamingConfig.Config;
import com.baeldung.boot.naming.entity.Preference;
import org.assertj.core.api.SoftAssertions;
import org.hibernate.boot.Metadata;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Table;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collection;
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(properties = {
"spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl",
"spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl",
})
@Import(Config.class)
public class StrategyLegacyHbmImplIntegrationTest extends NamingConfig {
@Test
public void givenLegacyHbmImplNamingNamingStrategy_whenCreateDatabase_thenGetStrategyNames() {
Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
String entity = Preference.class.getCanonicalName();
PersistentClass persistentClass = metadata.getEntityBinding(entity);
Collection<Table> tables = metadata
.getDatabase()
.getDefaultNamespace()
.getTables();
Table preferenceTable = persistentClass.getTable();
String tableNameExpected = "Account_preferences";
Table accountPreferencesTable = tables
.stream()
.filter(table -> table
.getName()
.equals(tableNameExpected))
.findFirst()
.get();
String implicitNameExpected = "account";
String implicitNameCreated = preferenceTable
.getColumn(3)
.getName();
String tableNameCreated = accountPreferencesTable.getName();
SoftAssertions.assertSoftly(softly -> {
softly
.assertThat(implicitNameCreated)
.isEqualTo(implicitNameExpected);
softly
.assertThat(tableNameCreated)
.isEqualTo(tableNameExpected);
});
}
}
@@ -0,0 +1,34 @@
package com.baeldung.boot.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.domain.User;
import com.baeldung.boot.repository.UserRepository;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by adam.
*/
@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("multiplesqlfiles")
public class UserRepositoryMultipleSqlFilesIntTest {
@Autowired private UserRepository userRepository;
@Test
public void givenTwoImportFilesWhenFindAllShouldReturnSixUsers() {
Collection<User> users = userRepository.findAll();
assertThat(users.size()).isEqualTo(6);
}
}
@@ -0,0 +1,68 @@
package com.baeldung.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableJpaRepositories(basePackages = { "com.baeldung.repository", "com.baeldung.boot.repository" })
@EnableTransactionManagement
@Profile("test") //only required to allow H2JpaConfig and H2TestProfileJPAConfig to coexist in same project
//this demo project is showcasing several ways to achieve the same end, and class-level
//Profile annotations are only necessary because the different techniques are sharing a project
public class H2TestProfileJPAConfig {
@Autowired
private Environment env;
@Bean
@Profile("test")
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
dataSource.setUsername("sa");
dataSource.setPassword("sa");
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" });
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return hibernateProperties;
}
}
@@ -0,0 +1,81 @@
package com.baeldung.springbootcrudapp.application.tests;
import com.baeldung.springbootcrudapp.application.controllers.UserController;
import com.baeldung.springbootcrudapp.application.entities.User;
import com.baeldung.springbootcrudapp.application.repositories.UserRepository;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
public class UserControllerUnitTest {
private static UserController userController;
private static UserRepository mockedUserRepository;
private static BindingResult mockedBindingResult;
private static Model mockedModel;
@BeforeClass
public static void setUpUserControllerInstance() {
mockedUserRepository = mock(UserRepository.class);
mockedBindingResult = mock(BindingResult.class);
mockedModel = mock(Model.class);
userController = new UserController(mockedUserRepository);
}
@Test
public void whenCalledshowSignUpForm_thenCorrect() {
User user = new User("John", "john@domain.com");
assertThat(userController.showSignUpForm(user)).isEqualTo("add-user");
}
@Test
public void whenCalledaddUserAndValidUser_thenCorrect() {
User user = new User("John", "john@domain.com");
when(mockedBindingResult.hasErrors()).thenReturn(false);
assertThat(userController.addUser(user, mockedBindingResult, mockedModel)).isEqualTo("index");
}
@Test
public void whenCalledaddUserAndInValidUser_thenCorrect() {
User user = new User("John", "john@domain.com");
when(mockedBindingResult.hasErrors()).thenReturn(true);
assertThat(userController.addUser(user, mockedBindingResult, mockedModel)).isEqualTo("add-user");
}
@Test(expected = IllegalArgumentException.class)
public void whenCalledshowUpdateForm_thenIllegalArgumentException() {
assertThat(userController.showUpdateForm(0, mockedModel)).isEqualTo("update-user");
}
@Test
public void whenCalledupdateUserAndValidUser_thenCorrect() {
User user = new User("John", "john@domain.com");
when(mockedBindingResult.hasErrors()).thenReturn(false);
assertThat(userController.updateUser(1l, user, mockedBindingResult, mockedModel)).isEqualTo("index");
}
@Test
public void whenCalledupdateUserAndInValidUser_thenCorrect() {
User user = new User("John", "john@domain.com");
when(mockedBindingResult.hasErrors()).thenReturn(true);
assertThat(userController.updateUser(1l, user, mockedBindingResult, mockedModel)).isEqualTo("update-user");
}
@Test(expected = IllegalArgumentException.class)
public void whenCalleddeleteUser_thenIllegalArgumentException() {
assertThat(userController.deleteUser(1l, mockedModel)).isEqualTo("index");
}
}
@@ -0,0 +1,46 @@
package com.baeldung.springbootcrudapp.application.tests;
import com.baeldung.springbootcrudapp.application.entities.User;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class UserUnitTest {
@Test
public void whenCalledGetName_thenCorrect() {
User user = new User("Julie", "julie@domain.com");
assertThat(user.getName()).isEqualTo("Julie");
}
@Test
public void whenCalledGetEmail_thenCorrect() {
User user = new User("Julie", "julie@domain.com");
assertThat(user.getEmail()).isEqualTo("julie@domain.com");
}
@Test
public void whenCalledSetName_thenCorrect() {
User user = new User("Julie", "julie@domain.com");
user.setName("John");
assertThat(user.getName()).isEqualTo("John");
}
@Test
public void whenCalledSetEmail_thenCorrect() {
User user = new User("Julie", "julie@domain.com");
user.setEmail("john@domain.com");
assertThat(user.getEmail()).isEqualTo("john@domain.com");
}
@Test
public void whenCalledtoString_thenCorrect() {
User user = new User("Julie", "julie@domain.com");
assertThat(user.toString()).isEqualTo("User{id=0, name=Julie, email=julie@domain.com}");
}
}
@@ -0,0 +1,31 @@
package com.baeldung.springbootdatasourceconfig.application.tests;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.springbootdatasourceconfig.application.entities.User;
import com.baeldung.springbootdatasourceconfig.application.repositories.UserRepository;
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryIntegrationTest {
@Autowired
private UserRepository userRepository;
@Test
public void whenCalledSave_thenCorrectNumberOfUsers() {
userRepository.save(new User("Bob", "bob@domain.com"));
List<User> users = (List<User>) userRepository.findAll();
// 2 additional users are saved in the CommandLineRunner bean
assertThat(users.size()).isEqualTo(3);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.springboothibernate.application.tests;
import com.baeldung.springboothibernate.application.models.Book;
import com.baeldung.springboothibernate.application.services.BookService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BookServiceUnitTest {
@Autowired
private BookService bookService;
@Test
public void whenApplicationStarts_thenHibernateCreatesInitialRecords() {
List<Book> books = bookService.list();
Assert.assertEquals(books.size(), 3);
}
}
@@ -0,0 +1,61 @@
package com.baeldung.springboothsqldb.application.tests;
import com.baeldung.springboothsqldb.application.entities.Customer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CustomerControllerUnitTest {
private static MediaType MEDIA_TYPE_JSON;
@Autowired
private MockMvc mockMvc;
@Before
public void setUpJsonMediaType() {
MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
}
@Test
public void whenPostHttpRequesttoCustomers_thenStatusOK() throws Exception {
Customer customer = new Customer("John", "john@domain.com");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter();
String requestJson = objectWriter.writeValueAsString(customer);
this.mockMvc
.perform(MockMvcRequestBuilders.post("/customers")
.contentType(MEDIA_TYPE_JSON)
.content(requestJson)
)
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void whenGetHttpRequesttoCustomers_thenStatusOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/customers"))
.andExpect(MockMvcResultMatchers.content().contentType(MEDIA_TYPE_JSON))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
@@ -0,0 +1,37 @@
package com.baeldung.springbootinitialload.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.jdbc.SqlConfig.TransactionMode;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.repository.EmployeeRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Sql({"/employees_schema.sql", "/import_employees.sql"})
public class SpringBootInitialLoadIntegrationTest {
@Autowired
private EmployeeRepository employeeRepository;
@Test
public void testLoadDataForTestClass() {
assertEquals(3, employeeRepository.findAll()
.size());
}
@Test
@Sql(scripts = {"/import_senior_employees.sql"}, config = @SqlConfig(encoding = "utf-8", transactionMode = TransactionMode.ISOLATED))
public void testLoadDataForTestCase() {
assertEquals(5, employeeRepository.findAll()
.size());
}
}
@@ -0,0 +1,31 @@
package com.baeldung.springbootinitialload.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.jdbc.SqlConfig.TransactionMode;
import org.springframework.test.context.jdbc.SqlGroup;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
import com.baeldung.boot.repository.EmployeeRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@SqlGroup({ @Sql(scripts = "/employees_schema.sql", config = @SqlConfig(transactionMode = TransactionMode.ISOLATED)),
@Sql("/import_employees.sql")})
public class SpringBootSqlGroupAnnotationIntegrationTest {
@Autowired
private EmployeeRepository employeeRepository;
@Test
public void testLoadDataForTestCase() {
assertEquals(3, employeeRepository.findAll().size());
}
}
@@ -0,0 +1,25 @@
package com.baeldung.tomcatconnectionpool.test.application;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.tomcatconnectionpool.application.SpringBootConsoleApplication;
import static org.assertj.core.api.Assertions.*;
import org.springframework.boot.test.context.SpringBootTest;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringBootConsoleApplication.class})
public class SpringBootTomcatConnectionPoolIntegrationTest {
@Autowired
private DataSource dataSource;
@Test
public void givenTomcatConnectionPoolInstance_whenCheckedPoolClassName_thenCorrect() {
assertThat(dataSource.getClass().getName()).isEqualTo("org.apache.tomcat.jdbc.pool.DataSource");
}
}
@@ -0,0 +1 @@
spring.jpa.properties.hibernate.hbm2ddl.import_files=import_active_users.sql,import_inactive_users.sql
@@ -0,0 +1,16 @@
# spring.datasource.x
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
spring.jpa.properties.hibernate.hbm2ddl.import_files=migrated_users.sql, import_books.sql
spring.datasource.data=import_*_users.sql
@@ -0,0 +1,8 @@
drop table EMPLOYEES if exists;
create table EMPLOYEES(
ID int not null AUTO_INCREMENT,
NAME varchar(100) not null,
TITLE varchar(100),
PRIMARY KEY ( ID )
);
@@ -0,0 +1,3 @@
insert into USERS(name, status, id) values('Peter', 1, 1);
insert into USERS(name, status, id) values('David', 1, 2);
insert into USERS(name, status, id) values('Ed', 1, 3);
@@ -0,0 +1,3 @@
insert into book values(1, 'The Tartar Steppe');
insert into book values(2, 'Poem Strip');
insert into book values(3, 'Restless Nights: Selected Stories of Dino Buzzati');
@@ -0,0 +1,3 @@
insert into EMPLOYEES values(1, 'Harsha', 'Developer');
insert into EMPLOYEES values(2, 'John', 'Tester');
insert into EMPLOYEES values(3, 'Ram', 'Manager');
@@ -0,0 +1,3 @@
insert into users(name, status, id) values('Monica', 0, 4);
insert into users(name, status, id) values('Paul', 0, 5);
insert into users(name, status, id) values('George', 0, 6);
@@ -0,0 +1,2 @@
insert into EMPLOYEES values(4, 'Eric', 'Senior Developer');
insert into EMPLOYEES values(5, 'Vidhyaah', 'Senior Manager');
@@ -0,0 +1,3 @@
insert into USERS(name, status, id) values('Peter', 1, 7);
insert into USERS(name, status, id) values('David', 1, 8);
insert into USERS(name, status, id) values('Ed', 1, 9);