Error creating bean with name 'embeddedKafka': Invocation of init method failed; nested exception is kafka.common.KafkaException: - spring

I am using the spring cloud contrat to test a kafkaListsener of my service. I use EmbeddedKafka together with the spring cloud contract.
The listener in my service is implemeneted by #KafkaListener from spring kafka.
The contract test I have is like below:
#EmbeddedKafka
#SpringBootTest(classes = {ServiceApplication.class},
properties = {"stubrunner.kafka.enabled=true",
"stubrunner.stream.enabled=false",
"spring.cloud.stream.function.autodetect=false"})
public class EventContractTest {
#Autowired
private StubTrigger stubTrigger;
#SpyBean
#Qualifier("KafkaEventListener")
private EventListener eventListener;
#BeforeEach
public void setup() throws ExecutionException, InterruptedException {
Mockito.doNothing().when(eventListener).onEventReceived(any(), any());
}
#Test
public void kafkaEventTest() throws ExecutionException, InterruptedException {
stubTrigger.trigger("kafka-event");
ArgumentCaptor<Event> eventArgumentCaptor = ArgumentCaptor.forClass(Event.class);
ArgumentCaptor<Bytes> headerArgumentCaptor = ArgumentCaptor.forClass(Bytes.class);
verify(eventListener, timeout(5000).times(1)).
onEventReceived(eventArgumentCaptor.capture(), headerArgumentCaptor.capture());
....
}
#Test
public void kafkaEventTest2() throws ExecutionException, InterruptedException {
stubTrigger.trigger("kafka-event-2");
ArgumentCaptor<Event> eventArgumentCaptor = ArgumentCaptor.forClass(Event.class);
ArgumentCaptor<Bytes> headerArgumentCaptor = ArgumentCaptor.forClass(Bytes.class);
verify(eventListener, timeout(5000).times(1)).
onEventReceived(eventArgumentCaptor.capture(), headerArgumentCaptor.capture());
....
}
}
when run the tests case, in most cases it will pass, but it will randomlly fail with the following exception:
givenEventFromContract_whenCancelSubscription_thenTriggerSubscriptionChangedKafkaEvent
Time elapsed: 0.002 s <<< ERROR! 14:12:43
java.lang.IllegalStateException: Failed to load ApplicationContext
14:12:43 Caused by:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'embeddedKafka': Invocation of init method
failed; nested exception is kafka.common.KafkaException: 14:12:43
Caused by: kafka.common.KafkaException: 14:12:43 Caused by:
java.util.concurrent.TimeoutException 14:12:43 14:12:43 [ERROR]
givenEventFromContract_whenDeleteSubscription_thenTriggerSubscriptionDeletedKafkaEvent
Time elapsed: 25.891 s <<< ERROR! 14:12:43
java.lang.IllegalStateException: java.util.concurrent.TimeoutException
14:12:43 at
And below are my kafka relevant configuration:
# -- Kafka with PLAINTEXT authentication --
com.sap.kafka.enabled=false
spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}
spring.kafka.consumer.group-id=test
spring.kafka.consumer.properties.auto.offset.reset=earliest
spring.kafka.topics.default.replication-factor=1
spring.kafka.topics.default.partition-count=1
spring.kafka.topics.default.min-in-sync-replicas=1
Does someone know what was the issue? is this a bug of spring kafka?

Related

SpringBootTest failing with 'IllegalStateException - No ServletContext set'

I have a pretty simple #SpringBootTest :
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {...})
public class MyApplicationTest {
#Test
public void anyTest() { ... }
}
It was working as expected until we've added #EnableSchedulerLock (from Shedlock) on the MyApplication.java file.
Since, we're experiencing this issue :
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582)
... 46 common frames omitted
Caused by: java.lang.IllegalStateException: No ServletContext set
at org.springframework.util.Assert.state(Assert.java:73)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:483)
This happends when Spring tries to instanciate its resourceHandlerMapping :
#Bean
public HandlerMapping resourceHandlerMapping() {
Assert.state(this.applicationContext != null, "No ApplicationContext set");
Assert.state(this.servletContext != null, "No ServletContext set");
...
It's like this #Bean is created before the setServletContext (from WebMvcConfigurationSupport) is called.
As mentioned by Lukas, this error has been fixed in the latest version of Shedlock.
Upgrading Shedlock's version from 2.2.0 to 2.5.0 fixes the issue.

java.lang.IllegalStateException: Failed to load ApplicationContext-How to test main class of Spring-boot application

I have a spring-boot application where my #SpringBootApplication starter class looks like a standard one and getting Caused by:
org.springframework.beans.factory.BeanDefinitionStoreException: Failed
to parse configuration class [com.abct.ECRRestServer];
nested exception is java.io.FileNotFoundException: Could not open
ServletContext resource [/application.properties]
#RunWith(SpringRunner.class)
#SpringBootTest
public class ECRRestServerTest {
#Test
public void contextTest() {
}
}
Encountering below issue.
2019-04-27 18:51:25.732 ERROR 15096 --- [ main]
o.s.test.context.TestContextManager : Caught exception while
allowing TestExecutionListener
[org.springframework.test.context.web.ServletTestExecutionListener#78e117e3]
to prepare test instance [com.abct.ECRRestServerTest#16ecee1]
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException:
Failed
to parse configuration class [com.abct.ECRRestServer]; nested
exception is java.io.FileNotFoundException: Could not open
ServletContext resource [/applicati
on.properties]

NullPointerException from ibatis when using FactoryBeanPostProcessor

I revise some bean definition through a customized BeanFactoryPostProcessor
When the web application startup, it failed:
#Component
public class RPCTimeoutPostProcessor implements BeanFactoryPostProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(RPCTimeoutPostProcessor.class);
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
overriderThriftTimeoutPolicy(beanFactory);
}
private void overriderThriftTimeoutPolicy(ConfigurableListableBeanFactory beanFactory) {
Map<String, ThriftClientProxy> map = beanFactory.getBeansOfType(ThriftClientProxy.class);
Set<String> keySet = map.keySet();
}
}
[WARNING] Failed startup of context o.m.j.p.JettyWebAppContext
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'baseSystemApi': Unsatisfied dependency
expressed through field 'appConfigService'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'appConfigService': Invocation of init method
failed; nested exception is org.mybatis.spring.MyBatisSystemException:
nested exception is org.apache.ibatis.exceptions.PersistenceException:
Error querying database. Cause: java.lang.NullPointerException The
error may exist in com/xxx/dao/WmAppTextDao.java (best guess) The
error may involve com.xxx.dao.WmAppTextDao.getAll The error occurred
while executing a query Cause: java.lang.NullPointerException at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)

Usage of Spring #ConfigurationProperties gives nullpointer when running tests, JHipster app

I have implemented a simple file upload routine using Spring Boot ConfigurationProperties annotation so I can load the directory from my YAML configuration file:
Service:
#Service
public class FileSystemStorageService implements StorageService {
private final Logger log = LoggerFactory.getLogger(FileSystemStorageService.class);
private final Path pictureLocation;
#Autowired
public FileSystemStorageService(StorageProperties storageProperties) {
pictureLocation = Paths.get(storageProperties.getUpload());
}
And the StorageProperties:
#Component
#ConfigurationProperties("nutrilife.meals")
public class StorageProperties {
private String upload;
public String getUpload() {
return upload;
}
public void setUpload(String upload) {
this.upload= upload;
}
}
In the yaml file I have:
nutrilife:
meals:
upload: /$full_path_to_my_upload_dir
This works perfectly in normal Spring Boot runtime but the problem starts when I try to run my integration tests, it throws the error:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileSystemStorageService' defined in file [/home/mmaia/git/nutrilife/build/classes/main/com/getnutrilife/service/upload/FileSystemStorageService.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.getnutrilife.service.upload.FileSystemStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.getnutrilife.service.upload.FileSystemStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
So basically during tests the YAML file configuration looks like it's not being properly picked up. I am new to Spring. How can I fix it?
try adding the #value annotation :
#Value("upload")
private String upload;
The above answer is valid for application.properties config.
it also works with yaml as well.
You may find your correct correct yaml config here :
24.6 Using YAML instead of Properties

Spring Java config exception

I am trying to switch from xml config to java config and getting the following exception when starting the application.
Caused by: java.lang.ClassCastException: $Proxy188 cannot be cast to org.springframework.format.support.FormattingConversionService
This exception is thrown on the first line of the following method:
#Override
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter();
adapter.setIgnoreDefaultModelOnRedirect(true);
return adapter;
}
Any idea why this is failing?

Resources