Моё весеннее загрузочное приложение использует два разных источника данных.Я реализовал две конечные точки, чтобы убедиться, что он работает для разных источников данных.Теперь я хочу приступить к реализации с тестами, но там я не смог начать свой интеграционный тест с базой данных h2.Ранее я использовал те же application.properties, что и в производственном приложении, и тест интеграции работал, но теперь он прерывается, потому что
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jwtAuthorizationTokenFilter' defined in file [G:\repos\bar-bar\bar-rest-jee\bar-spring-rest\out\production\classes\de\bar\bar\rest\barspringrest\authentication\JwtAuthorizationTokenFilter.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'UserDetailsService': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImpl' defined in file [G:\repos\bar-bar\bar-rest-jee\bar-spring-rest\out\production\classes\de\bar\bar\rest\barspringrest\UserManagement\UserServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserRepository': Cannot create inner bean '(inner bean)#76a805b7' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#76a805b7': Cannot resolve reference to bean 'managerEntityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'managerEntityManagerFactory' defined in class path resource [de/bar/bar/rest/barspringrest/configuration/DataSource/ManagerDataSourceConfig.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Здесь мой IntegrationTestClass
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations="classpath:application-test.properties")
@Transactional
public class UserControllerTest {
@LocalServerPort
private int port;
TestRestTemplate restTemplate = new TestRestTemplate();
HttpHeaders headers = new HttpHeaders();
@Autowired
private WfcSpringRestApplication controller;
@Test
public void contextLoads(){
assertThat(controller).isNotNull();
}
@Test
public void testFindUserById() throws JSONException {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzeXNhZG0iLCJleHAiOjE1NTM3ODU4NzEsImlhdCI6MTU1MzE4MTA3MX0.P5LnOW5_sGE2KZDJNx0LmzSbn6zFqF9tSHDkh2uxCRmisO9KpGZ1a2vYieKB8BQtM7TP1ywR9LRRoOMy2aHrIA");
HttpEntity<String> entity = new HttpEntity<>(null, headers);
ResponseEntity<String> response = restTemplate.exchange(createUrlWithPort("/user/4295833531"), HttpMethod.GET, entity, String.class);
System.out.println("Status code: " + response.getStatusCode());
System.out.println("headers: " + response.getHeaders());
String expected = "{\"id\":4295833531}";
JSONAssert.assertEquals(expected, response.getBody(), false);
}
/*
@Test
public void testCreateUser() throws Exception {
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
ResponseEntity<String> response = restTemplate.exchange(
createUrlWithPort("/user"), HttpMethod.POST, entity, String.class);
String actual = response.getHeaders().get(HttpHeaders.LOCATION).get(0);
assertTrue(actual.contains("/user"));
}
*/
private String createUrlWithPort(String uri) {
return "http://localhost:" + port + uri;
}
}
И это один из моихИсточник данных, который упоминается в сообщении об ошибке
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "managerEntityManagerFactory",
transactionManagerRef = "managerTransactionManager",
basePackages = {"de.bar.bar.rest.barspringrest.UserManagement"}
)
@EnableTransactionManagement
public class ManagerDataSourceConfig {
@Bean(name = "managerDataSourceProperties")
@ConfigurationProperties("app.datasource.manager")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
@Bean(name = "managerDataSource")
@ConfigurationProperties("app.datasource.manager.configuration")
public DataSource dataSource(DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}
@Bean(name = "managerEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean managerEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(dataSource(dataSourceProperties()));
entityManager.setPackagesToScan(new String[]{"de.bar.bar.rest.barspringrest.UserManagement"});
entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManager.setJpaPropertyMap(additionalJpaProperties());
return entityManager;
}
Map<String, ?> additionalJpaProperties() {
Map<String, String> map = new HashMap<>();
map.put("hibernate.show_sql", "true");
map.put("hibernate.hbm2ddl.auto", "update");
map.put("hibernate.physical_naming_strategy","de.bar.bar.rest.barspringrest.configuration.barPhysicalNamingStrategy");
return map;
}
@Bean(name = "managerTransactionManager")
public JpaTransactionManager transactionManager(@Qualifier("managerEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
Здесь мое application-test.properties
app.datasource.server.datasource.url=jdbc:h2:mem:scserver
app.datasource.server.username=sa
app.datasource.server.password=
app.datasource.server.driverClassName=org.h2.Driver
app.datasource.server.jpa.database-platform=org.hibernate.dialect.H2Dialect
#app.datasource.server.url=jdbc:sqlserver://192.168.101.14:1433;database=TEST_SCServer
#app.datasource.server.username=sa
#app.datasource.server.password=
#app.datasource.server.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
app.datasource.manager.datasource.url=jdbc:h2:mem:scmanager
app.datasource.manager.username=sa
app.datasource.manager.password=
app.datasource.manager.driverClassName=org.h2.Driver
app.datasource.manager.jpa.database-platform=org.hibernate.dialect.H2Dialect
#app.datasource.manager.url=jdbc:sqlserver://192.168.101.14:1433;database=TEST_SCManager
#app.datasource.manager.username=sa
#app.datasource.manager.password=
#app.datasource.manager.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
#spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
# The SQL dialect makes Hibernate generate better SQL for the chosen database
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=create-drop
#logging
logging.level.root=info
logging.file=wfc-spring-rest.log
#required for SpringBootTest does not know why
spring.main.allow-bean-definition-overriding=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
Я не понимаю, почему оно работает как приложение с весенней загрузкой, но в моем тестовом примере это не так.Работа.Есть идеи?