This exception may occur if matchers are combined with raw values - spring

My Mock call is like below :
BDDMockito.given(restTemplate.exchange(url,
HttpMethod.POST,
BDDMockito.any(),
Response.class)
).willReturn(responseEntity);
but i am getting below errors . please help me out on this???????
4 matchers expected, 1 recorded:
-> at com.esrx.aggregation.service.servicecaller.GetSpecalityInventoryItemsCallerTest.getSpecalityInventoryItemsCallPositiveTest(GetSpecalityInventoryItemsCallerTest.java:67)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
, mergedContextConfiguration = [WebMergedContextConfiguration#61375dff testClass = GetSpecalityInventoryItemsCallerTest, locations = '{}', classes = '{class com.esrx.aggregation.application.Main, class com.esrx.aggregation.application.Main}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:/application.properties, classpath:/service.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer#351d00c0, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#35d019a3, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#78691363], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
2017-12-19 15:59:53.085 INFO 10140 --- [ Thread-5] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#5a62b2a4: startup date [Tue Dec 19 15:59:35 IST 2017]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#3e6f3f28

That's because you can't mix matchers with raw values. If you use matchers then you need to use matchers for all arguments. If you still want to match an exact value you can use the .eq() matcher:
BDDMockito.given(restTemplate.exchange(Mockito.eq(url), Mockito.eq(HttpMethod.POST), BDDMockito.any(), Mockito.eq(Response.class))).willReturn(responseEntity)

Related

Spring JPA Hibernate "Unable to access TransactionManager or UserTransaction to make physical transaction delegate"

i aims make working hibernate with JPA EntityManager in order to not change code if i change my ORM in the future, i get an error "Unable to access TransactionManager or UserTransaction to make physical transaction delegate" when i launch my class test, bellow source code :
Config.java :
package repository.jpa;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.jta.JtaTransactionManager;
#Configuration
#EnableTransactionManagement
public class Config {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};
#Bean
public DataSource dataSource1() {
return new EmbeddedDatabaseBuilder()
.setName("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1")
.setType(EmbeddedDatabaseType.H2)
//.addScript("classpath:db/schema.sql")
//.addScript("classpath:db/data.sql")
.build();
}
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean localEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
localEntityManagerFactoryBean.setJtaDataSource(dataSource1());
localEntityManagerFactoryBean.setPackagesToScan("model");
localEntityManagerFactoryBean.setJpaVendorAdapter(hibernateJpaVendorAdapter());
localEntityManagerFactoryBean.setPersistenceUnitName("unit1");
Properties prop = new Properties();
prop.put("hibernate.dialect",
"org.hibernate.dialect.H2Dialect");
localEntityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());
localEntityManagerFactoryBean.afterPropertiesSet();
localEntityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
return localEntityManagerFactoryBean;
}
private HibernateJpaVendorAdapter hibernateJpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter =new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
return hibernateJpaVendorAdapter;
}
#Bean
public PlatformTransactionManager transactionManager(#Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager(entityManagerFactory().getNativeEntityManagerFactory());
return txManager;
}
private Properties jpaHibernateProperties() {
Properties properties = new Properties();
//properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
//properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
//properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
//properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
//properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, true);
properties.put("hibernate.dialect","org.hibernate.dialect.H2Dialect");
return properties;
}
#Bean
public PersonRepository personRepository() {
return new PersonRepository();
}
}
PersonRepository.java :
package repository.jpa;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import model.Person;
import repository.jdbctemplate.IPersonRepository;
public class PersonRepository implements IPersonRepository {
#PersistenceContext(unitName = "unit1")
private EntityManager entityManager;
private EntityManager session() {
return entityManager;
}
#Override
//#Transactional( value= TxType.REQUIRES_NEW)
public Person getPersonById(String id) {
long idLong = Long.valueOf(id);
return (Person) session().createQuery("from Person where id = :id").setParameter("id", idLong).getResultList();
}
#Override
public boolean isTableCreated(String tableName) {
int count = (int) session().createQuery("select count(*) from shema_information where table_name='PERSON'").getSingleResult();
return count > 0 ? true : false;
}
#Override
public void createPersonTable() {
session().createQuery("create table Person(id number, name varchar, salary float)");
}
#Override
public int insertPerson(long id, String name, float salary) {
int count = session().createQuery("insert into Person values(?,?,?)").setParameter("id", id)
.setParameter("name", name).setParameter("salary", salary).executeUpdate();
return count;
}
#Override
public List<Map<String, Object>> getPerosnLinesAsListMap() {
// TODO Auto-generated method stub
return null;
}
#Override
#Transactional
public List<Person> findAll() {
return session().createQuery("select p from Person p").getResultList();
}
}
PersonRepositoryTest.java :
package test.repository.jpa;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
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.jdbc.Sql;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import model.Person;
import repository.jdbctemplate.IPersonRepository;
import repository.jpa.Config;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {Config.class})
#Sql(scripts = "classpath:db/schema.sql")
#Sql(scripts = "classpath:db/data.sql")
public class PersonRepositoryTest {
#Autowired
IPersonRepository personRepo;
//#Test
public void getPersonById_RightId_NotNull() {
Person person = personRepo.getPersonById("2");
assertNotNull(person);
}
#Test
public void findAll_2Ecords_OK() {
List<Person> persons = personRepo.findAll();
assertEquals(2,persons.size());
}
}
bellow the error stack obtained when launch PersonRepositoryTest.java class test :
15:16:02.459 [main] DEBUG org.hibernate.loader.entity.plan.EntityLoader - Static select for entity model.Person [NONE]: select person0_.id as id1_0_0_, person0_.name as name2_0_0_, person0_.salary as salary3_0_0_ from Person person0_ where person0_.id=?
15:16:02.486 [main] DEBUG org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator - No actions specified; doing nothing
15:16:02.487 [main] DEBUG org.hibernate.query.spi.NamedQueryRepository - Checking 0 named HQL queries
15:16:02.487 [main] DEBUG org.hibernate.query.spi.NamedQueryRepository - Checking 0 named SQL queries
15:16:02.491 [main] DEBUG org.hibernate.service.internal.SessionFactoryServiceRegistryImpl - EventListenerRegistry access via ServiceRegistry is deprecated. Use `sessionFactory.getEventEngine().getListenerRegistry()` instead
15:16:02.496 [main] DEBUG org.hibernate.internal.SessionFactoryRegistry - Initializing SessionFactoryRegistry : org.hibernate.internal.SessionFactoryRegistry#6b63abdc
15:16:02.496 [main] DEBUG org.hibernate.internal.SessionFactoryRegistry - Registering SessionFactory: 43bdb8fe-219f-41d8-8c7e-48775ee764e5 (<unnamed>)
15:16:02.496 [main] DEBUG org.hibernate.internal.SessionFactoryRegistry - Not binding SessionFactory to JNDI, no JNDI name configured
15:16:02.497 [main] INFO org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'unit1'
15:16:02.526 [main] DEBUG org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'unit1'
15:16:02.526 [main] DEBUG org.hibernate.jpa.internal.util.LogHelper - PersistenceUnitInfo [
name: unit1
persistence provider classname: null
classloader: jdk.internal.loader.ClassLoaders$AppClassLoader#5387f9e0
excludeUnlistedClasses: true
JTA datasource: org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#21282ed8], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
15:16:02.747 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache#7d66e544 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 4, missCount = 1]
15:16:02.754 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Creating new transaction with name [test.repository.jpa.PersonRepositoryTest.findAll_2Ecords_OK]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
15:16:02.835 [main] DEBUG org.hibernate.stat.internal.StatisticsInitiator - Statistics initialized [enabled=false]
15:16:02.842 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Opened new EntityManager [SessionImpl(1428777808<open>)] for JPA transaction
15:16:02.850 [main] DEBUG org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl - JtaPlatform#retrieveTransactionManager returned null
15:16:02.851 [main] DEBUG org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl - Unable to access TransactionManager, attempting to use UserTransaction instead
15:16:02.851 [main] DEBUG org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl - JtaPlatform#retrieveUserTransaction returned null
15:16:02.851 [main] DEBUG org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl - JtaPlatform#retrieveTransactionManager returned null
15:16:02.851 [main] DEBUG org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl - Unable to access TransactionManager, attempting to use UserTransaction instead
15:16:02.851 [main] DEBUG org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl - JtaPlatform#retrieveUserTransaction returned null
15:16:02.853 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Could not rollback EntityManager after failed transaction begin
org.hibernate.resource.transaction.backend.jta.internal.JtaPlatformInaccessibleException: Unable to access TransactionManager or UserTransaction to make physical transaction delegate
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.makePhysicalTransactionDelegate(JtaTransactionCoordinatorImpl.java:257)
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.getTransactionDriverControl(JtaTransactionCoordinatorImpl.java:231)
at org.hibernate.engine.transaction.internal.TransactionImpl.<init>(TransactionImpl.java:46)
at org.hibernate.internal.AbstractSharedSessionContract.accessTransaction(AbstractSharedSessionContract.java:463)
at org.hibernate.internal.AbstractSharedSessionContract.getTransaction(AbstractSharedSessionContract.java:456)
at org.hibernate.internal.AbstractSessionImpl.getTransaction(AbstractSessionImpl.java:23)
at org.springframework.orm.jpa.JpaTransactionManager.closeEntityManagerAfterFailedBegin(JpaTransactionManager.java:506)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:466)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.startTransaction(AbstractPlatformTransactionManager.java:400)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:137)
at org.springframework.transaction.support.TransactionOperations.executeWithoutResult(TransactionOperations.java:67)
at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:279)
at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.lambda$executeSqlScripts$0(SqlScriptsTestExecutionListener.java:201)
at java.base/java.lang.Iterable.forEach(Iterable.java:75)
at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:201)
at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:148)
at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.beforeTestMethod(SqlScriptsTestExecutionListener.java:118)
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:293)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
15:16:02.855 [main] WARN org.springframework.test.context.TestContextManager - Caught exception while invoking 'beforeTestMethod' callback on TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#8458f04] for test method [public void test.repository.jpa.PersonRepositoryTest.findAll_2Ecords_OK()] and test instance [test.repository.jpa.PersonRepositoryTest#65f8f5ae]
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.resource.transaction.backend.jta.internal.JtaPlatformInaccessibleException: Unable to access TransactionManager or UserTransaction to make physical transaction delegate
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:467)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.startTransaction(AbstractPlatformTransactionManager.java:400)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:137)
at org.springframework.transaction.support.TransactionOperations.executeWithoutResult(TransactionOperations.java:67)
at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:279)
at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.lambda$executeSqlScripts$0(SqlScriptsTestExecutionListener.java:201)
at java.base/java.lang.Iterable.forEach(Iterable.java:75)
at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:201)
at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:148)
at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.beforeTestMethod(SqlScriptsTestExecutionListener.java:118)
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:293)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.hibernate.resource.transaction.backend.jta.internal.JtaPlatformInaccessibleException: Unable to access TransactionManager or UserTransaction to make physical transaction delegate
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.makePhysicalTransactionDelegate(JtaTransactionCoordinatorImpl.java:257)
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.getTransactionDriverControl(JtaTransactionCoordinatorImpl.java:231)
at org.hibernate.engine.transaction.internal.TransactionImpl.<init>(TransactionImpl.java:46)
at org.hibernate.internal.AbstractSharedSessionContract.accessTransaction(AbstractSharedSessionContract.java:463)
at org.hibernate.internal.AbstractSharedSessionContract.getTransaction(AbstractSharedSessionContract.java:456)
at org.hibernate.internal.AbstractSessionImpl.getTransaction(AbstractSessionImpl.java:23)
at org.springframework.orm.jpa.DefaultJpaDialect.beginTransaction(DefaultJpaDialect.java:70)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:421)
... 33 common frames omitted
15:16:02.856 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext [1552326679] from cache with key [[MergedContextConfiguration#65987993 testClass = PersonRepositoryTest, locations = '{}', classes = '{class repository.jpa.Config}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#28f2a10f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#7fee8714, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer#209da20d, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#21282ed8], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
15:16:02.857 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache#7d66e544 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 5, missCount = 1]
15:16:02.857 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext [1552326679] from cache with key [[MergedContextConfiguration#65987993 testClass = PersonRepositoryTest, locations = '{}', classes = '{class repository.jpa.Config}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#28f2a10f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#7fee8714, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer#209da20d, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#21282ed8], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
15:16:02.857 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache#7d66e544 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 6, missCount = 1]
15:16:02.858 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext [1552326679] from cache with key [[MergedContextConfiguration#65987993 testClass = PersonRepositoryTest, locations = '{}', classes = '{class repository.jpa.Config}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#28f2a10f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#7fee8714, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer#209da20d, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#21282ed8], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
15:16:02.858 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache#7d66e544 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 7, missCount = 1]
15:16:02.860 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext [1552326679] from cache with key [[MergedContextConfiguration#65987993 testClass = PersonRepositoryTest, locations = '{}', classes = '{class repository.jpa.Config}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#28f2a10f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#7fee8714, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer#209da20d, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customiz

add transaction manager for a Couchbase app. in a SpringBoot 2 app for Junit tests

I have a SpringBoot 2 app that uses using Couchbase as a database with Spring Data Couchbase
I wnt to add a transaction manager to add the annotation #Transactional in the test to do the rollback, otherwise I get this error:
java.lang.IllegalStateException: Failed to retrieve PlatformTransactionManager for #Transactional test: [DefaultTestContext#3bf9ce3e testClass = RequestServiceIntegrationTest, testInstance = com.pxs.rqm.requestcrud.service.RequestServiceIntegrationTest#1ebcfcf1, testMethod = shouldSaveWhenDataIsOK#RequestServiceIntegrationTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration#16610890 testClass = RequestServiceIntegrationTest, locations = '{}', classes = '{class com.pxs.rqm.requestcrud.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#971d0d8, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#564718df, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#36f0f1be, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#2145433b], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]]
at org.springframework.util.Assert.state(Assert.java:94)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:185)
Although we try to support most of the Spring interface, the #Transactional interface is specific to Relational Databases.
Updates in Couchbase are atomic (all or nothing), and as the way you model data is different than relational you usually don't need transactions that often. Think about a user, for instance, all the data related to it (preferences, address, credit cards) would be stored in the same document, that is why transactions are not usually necessary in this case.
However, if you need to update multiple documents at the same time, then you might consider using the new support for transactions which is available only on the SDK 3 for now (https://www.couchbase.com/transactions)

Hibernate sql query format in console

I'm trying to log the sql queries i'm calling from a .xml file. The problem i'm facing is that when i see the log, it's not well formatted. Also, i don't know why it appears repeated...
[main] INFO org.dozer.DozerBeanMapper - Initializing a new instance of dozer bean mapper.
[main] INFO org.dozer.DozerBeanMapper - Initializing a new instance of dozer bean mapper.
[main] INFO org.springframework.orm.hibernate5.HibernateTransactionManager - Using DataSource [org.apache.commons.dbcp2.BasicDataSource#1f03fba0] of Hibernate SessionFactory for HibernateTransactionManager
[main] INFO org.springframework.aop.framework.CglibAopProxy - Unable to proxy method [public final void com.servicios.test.TestRestauranteManager.findProveedoresByIdRestaurante() throws com.servicios.util.exceptions.AlergenosException] because it is final: All calls to this method via a proxy will NOT be routed to the target instance.
[main] INFO org.springframework.test.context.transaction.TransactionContext - Began transaction (1) for test context [DefaultTestContext#436bd4df testClass = TestRestauranteManager, testInstance = com.servicios.test.TestRestauranteManager#6848a051, testMethod = findProveedoresByIdRestaurante#TestRestauranteManager, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#149b0577 testClass = TestRestauranteManager, locations = '{classpath:test-applicationContext.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.hibernate5.HibernateTransactionManager#5740ff5e]; rollback [true]
select restaurant0_."ID_RESTAURANTE" as ID_RESTA1_4_0_, restaurant0_."DESCRIPCION" as DESCRIPC2_4_0_, restaurant0_."ID_CADENA_RESTAURANTE" as ID_CADEN3_4_0_ from "RESTAURANTE" restaurant0_ where restaurant0_."ID_RESTAURANTE"=?
Hibernate: select restaurant0_."ID_RESTAURANTE" as ID_RESTA1_4_0_, restaurant0_."DESCRIPCION" as DESCRIPC2_4_0_, restaurant0_."ID_CADENA_RESTAURANTE" as ID_CADEN3_4_0_ from "RESTAURANTE" restaurant0_ where restaurant0_."ID_RESTAURANTE"=?
binding parameter [1] as [BIGINT] - [0]
I would like to have something like
[main] INFO org.dozer.DozerBeanMapper - Initializing a new instance of dozer bean mapper. [main] INFO org.dozer.DozerBeanMapper -
Initializing a new instance of dozer bean mapper. [main] INFO
org.springframework.orm.hibernate5.HibernateTransactionManager - Using
DataSource [org.apache.commons.dbcp2.BasicDataSource#1f03fba0] of
Hibernate SessionFactory for HibernateTransactionManager [main] INFO
org.springframework.aop.framework.CglibAopProxy - Unable to proxy
method [public final void
com.servicios.test.TestRestauranteManager.findProveedoresByIdRestaurante()
throws com.servicios.util.exceptions.AlergenosException] because it is
final: All calls to this method via a proxy will NOT be routed to the
target instance. [main] INFO
org.springframework.test.context.transaction.TransactionContext -
Began transaction (1) for test context [DefaultTestContext#436bd4df
testClass = TestRestauranteManager, testInstance =
com.servicios.test.TestRestauranteManager#6848a051, testMethod =
findProveedoresByIdRestaurante#TestRestauranteManager, testException =
[null], mergedContextConfiguration =
[MergedContextConfiguration#149b0577 testClass =
TestRestauranteManager, locations =
'{classpath:test-applicationContext.xml}', classes = '{}',
contextInitializerClasses = '[]', activeProfiles = '{}',
propertySourceLocations = '{}', propertySourceProperties = '{}',
contextLoader =
'org.springframework.test.context.support.DelegatingSmartContextLoader',
parent = [null]]]; transaction manager
[org.springframework.orm.hibernate5.HibernateTransactionManager#5740ff5e];
Hibernate: select
p."DESCRIPCION" as "descripcion",
p."ID_PROVEEDOR" as "idProveedor"
from
"RESTAURANTE_PROVEEDOR" rp
inner join
"PROVEEDOR" p
on rp."ID_PROVEEDOR" = p."ID_PROVEEDOR"
where
rp."ID_RESTAURANTE" = ? binding parameter [1] as [BIGINT] - [0]
My log4j.properties is the following:
log4j.rootLogger=INFO, stdout
log4j.logger.org.hibernate=INFO
log4j.logger.org.hibernate.SQL=TRACE
log4j.logger.org.hibernate.type=ALL
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.rootConsola.layout.ConversionPattern=(%d{dd/MM/yyyy-HH:mm:ss}) %-5p: %-40c{1} - %m%n
And in my ApplicationContext.xml I have this
...
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="packagesToScan" value="com.servicios.vo"/>
<property name="mappingLocations">
<list>
<value>classpath*:hibernate/queries/**/*.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
...
Thanks in advance!!
The hibernate.format_sql setting does not apply to Exception reasons when something happens and an Exception is thrown that includes a SQL fragment.
In other words, hibernate.format_sql only applies when Hibernate writes the SQL it's about to execute to the logs, not when it's included as part of some Exception reason.

Maven Surefire Concurrent Modification Exception

When Maven builds my project and runs the unit tests, sometimes a concurrent modification exception is thrown (approximately 1 out of 5 times it will fail, the other times it will build successfully). But when I run the tests locally as unit tests, they all pass without the exception.
In my pom.xml file I have the Surefire plugin configured as:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<forkCount>1C</forkCount>
<reuseForks>true</reuseForks>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.19.1</version>
</dependency>
</dependencies>
</plugin>
However the stacktrace I get back does not mention what is causing the concurrent modification exception.
I have noticed that all tests pass on the build, but for some reason Maven reprints out the result of the test that has already passed but now has test exception ConcurrentModification.
I'm not sure what is causing the test result to be reprinted, or whether for some reason the test is being rerun at the same time while the first run of the test has not been completed since it is a parallel build? (Not sure why it would rerun a test)
Stacktrace
[Test executing]
13:48:24.869 [00001-main] DEBUG o.s.t.c.s.DirtiesContextTestExecutionListener - After test method: context [DefaultTestContext#375046d6 testClass = Tests, testInstance = com.application.Tests#179181c, testMethod = failingTest#Tests, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration#3f7b4a61 testClass = Tests, locations = '{}', classes = '{class com.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/app', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
13:48:24.869 [00001-main] DEBUG o.s.t.c.w.ServletTestExecutionListener - Resetting RequestContextHolder for test context [DefaultTestContext#375046d6 testClass = Tests, testInstance = com.application.Tests#179181c, testMethod = failingTest#Tests, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration#3f7b4a61 testClass = Test, locations = '{}', classes = '{class com.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/app', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]].
[Some other tests executing]
13:48:28.632 [00001-main] DEBUG o.s.t.c.s.DirtiesContextTestExecutionListener - After test method: context [DefaultTestContext#54fde1bc testClass = Tests, testInstance = com.application.Tests#57ffa818, testMethod = failingTest#Tests, testException = java.util.ConcurrentModificationException, mergedContextConfiguration = [WebMergedContextConfiguration#5247834f testClass = Tests, locations = '{}', classes = '{class com.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/app', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]], class dirties context [false], class mode [null], method dirties context [false].
13:48:28.632 [00001-main] DEBUG o.s.t.c.w.ServletTestExecutionListener - Resetting RequestContextHolder for test context [DefaultTestContext#54fde1bc testClass = Tests, testInstance = com.application.Tests#57ffa818, testMethod = failingTest#Tests, testException = java.util.ConcurrentModificationException, mergedContextConfiguration = [WebMergedContextConfiguration#5247834f testClass = Tests, locations = '{}', classes = '{class com.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', resourceBasePath = 'src/main/app', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]]].
failingTest(com.application.Tests) Time elapsed: 0 sec <<< ERROR!
java.util.ConcurrentModificationException
[Some other tests executing]
Results :
Tests in error:
Tests.failingTestĀ» ConcurrentModification
I am not sure what is causing the Concurrent Modification Exception or how to avoid this issue from occurring as it only happens sometimes, but it is the same test that fails and not other tests in my test suite.
I found out the issue was occurring because of a method which I had not mocked out which was creating and running a thread (even though the thread was not modifying any resources) - so I mocked it out and the issue seems to be resolved.
I was having the same issue, but it was related to the change made to Collections.sort() in Java 8. More information.

Error testing spring boot 1.4 application

I have very simple spring boot 1.4 application with one rest controller. When i tried to test the context loading of this i am getting error like below :-
13:29:03.623 [main] DEBUG o.s.t.c.j.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.628 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
13:29:03.632 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
13:29:03.641 [main] DEBUG o.s.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
13:29:03.644 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Neither #ContextConfiguration nor #ContextHierarchy found for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.650 [main] DEBUG o.s.b.t.c.SpringBootTestContextBootstrapper - #TestExecutionListeners is not present for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]: using defaults.
13:29:03.659 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
13:29:03.667 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
13:29:03.671 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
13:29:03.672 [main] INFO o.s.b.t.c.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#2db7a79b, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener#6950e31, org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener#b7dd107, org.springframework.test.context.support.DependencyInjectionTestExecutionListener#42eca56e, org.springframework.test.context.support.DirtiesContextTestExecutionListener#52f759d7, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener#7cbd213e, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#192d3247, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#3ecd23d9, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener#569cfc36]
13:29:03.674 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.674 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.690 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.690 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.691 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.691 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.692 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.692 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.695 [main] DEBUG o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext#67b467e9 testClass = FrontendServiceApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#47db50c5 testClass = FrontendServiceApplicationTests, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'null', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
13:29:03.696 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved #ProfileValueSourceConfiguration [null] for test class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.696 [main] DEBUG o.s.t.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests]
13:29:03.697 [main] DEBUG o.s.t.c.s.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext#67b467e9 testClass = FrontendServiceApplicationTests, testInstance = com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests#548ad73b, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#47db50c5 testClass = FrontendServiceApplicationTests, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'null', parent = [null]]]].
13:29:03.699 [main] ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener#b7dd107] to prepare test instance [com.byteobject.cloudsanthe.frontendservice.FrontendServiceApplicationTests#548ad73b]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.boot.test.autoconfigure.AutoConfigureReportTestExecutionListener.prepareTestInstance(AutoConfigureReportTestExecutionListener.java:49)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.IllegalArgumentException: Cannot load an ApplicationContext with a NULL 'contextLoader'. Consider annotating your test class with #ContextConfiguration or #ContextHierarchy.
at org.springframework.util.Assert.notNull(Assert.java:115)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:91)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 24 common frames omitted
13:29:03.705 [main] DEBUG o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext#67b467e9 testClass = FrontendServiceApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#47db50c5 testClass = FrontendServiceApplicationTests, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'null', parent = [null]]], class annotated with #DirtiesContext [false] with mode [null].
test class is :-
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class FrontendServiceApplicationTests {
#Test
public void contextLoads() {
}
}
And application class is :-
#SpringBootApplication
#ImportResource({"classpath:dbContext.xml", "classpath:dbClientMappingContext.xml"})
public class FrontendServiceApplication {
/**
* The main method.
*
* #param args the arguments
*/
public static void main(String[] args) {
SpringApplication.run(FrontendServiceApplication.class, args);
}
}
What i am doing wrong here?
It looks like Spring Boot cannot find your #SpringBootApplication class using classpath scanning.
So give the following a try:
#RunWith(SpringRunner.class)
#SpringBootTest(
classes = FrontendServiceApplication.class,
webEnvironment = WebEnvironment.RANDOM_PORT
)
public class FrontendServiceApplicationTests {
#Test
public void contextLoads() {
}
}

Resources