jUnit DataSource issue - jdbc

I'm trying to print the database table names, but for some reason I get (below) when I try to test the method
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
I've looked it up and apparently you have to set up the connection manually in the test class, else it won't work (but again, the topic I've read this was from 2008). Is there any way I could not do that?
public class ConnectionPool {
private static ConnectionPool pool = null;
private static DataSource dataSource = null;
private ConnectionPool(){
try{
InitialContext cx = new InitialContext();
this.dataSource = (DataSource) cx.lookup("java:/comp/env/jdbc/tut_web");
} catch (NamingException ex) {
Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static synchronized ConnectionPool getInstance(){
if(pool == null){
pool = new ConnectionPool();
}
return pool;
}
public Connection getConnection(){
try{
return this.dataSource.getConnection();
} catch (SQLException ex) {
Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public void closeConnection(Connection connection){
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(ConnectionPool.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/tut_web" auth="Container"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/tut_web?autoReconnect=true"
username="root" password="password"
maxActive="100" maxIdle="30" maxWait="10000"
logAbandoned="true" removeAbandoned="true"
removeAbandonedTimeout="60" type="javax.sql.DataSource" />
</Context>
Stacktree:
Apr 20, 2018 5:40:11 PM com.vio.db.config.ConnectionPool <init>
SEVERE: null
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.vio.db.config.ConnectionPool.<init>(ConnectionPool.java:27)
at com.vio.db.config.ConnectionPool.getInstance(ConnectionPool.java:35)
at com.vio.repository.CRUDReflection.<init>(CRUDReflection.java:27)
at com.vio.service.CRUDReflectionTEST.setUp(CRUDReflectionTEST.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.tools.ant.taskdefs.optional.junit.JUnit4TestMethodAdapter.run(JUnit4TestMethodAdapter.java:107)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:535)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1182)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:1033)

Related

Can't stub SimpleMessageListenerContainer isActive method [Spring AMQP Rabbit]

I'm trying to create unit tests for my Spring EventListeners that toggle SimpleMessageListenerContainer (start/stop).
The code I'm trying to test:
#Configuration
public class SpringEventsListeners {
private static CPLocation cpLocation = CPLoggingFactory.createCPLocation(SpringEventsListeners.class);
private ConfigurationServiceImpl configService;
//Constructor Injection for Testability.
public SpringEventsListeners(final ConfigurationServiceImpl configService) {
this.configService = configService;
}
/**
* Rabbit listeners might be started/stopped after a refresh depending on a property.
* In case a change is needed, we perform it.
*/
#EventListener(classes= { ApplicationReadyEvent.class, EnvironmentChangeEvent.class })
public void handleRabbitListenerToggle() {
String method = "handleRabbitListenerToggle";
cpLocation.info(method, "Received refresh event. Determining action.");
boolean shouldActivateRabbit = configService.shouldActivateRabbitListeners();
for (SimpleMessageListenerContainer container : configService.getAllRabbitSimpleMessageListenerContainers()) {
if (shouldActivateRabbit && !container.isActive()) {
container.start();
cpLocation.info(method, "Starting container: "+Arrays.toString(container.getQueueNames()));
}
else if (!shouldActivateRabbit && container.isActive()) {
container.shutdown();
cpLocation.info(method, "Shutting down container: "+Arrays.toString(container.getQueueNames()));
}
}
}
}
Minimal test (tests nothing):
#RunWith(MockitoJUnitRunner.class)
public class SpringEventsListenersTests {
#InjectMocks
private SpringEventsListeners classUnderTest;
#Mock
private ConfigurationServiceImpl mockConfigurationService;
#Mock
private SimpleMessageListenerContainer mockSimpleMessageListenerContainer;
#Test
public void testToggleTrue() {
//Given
given(mockConfigurationService.shouldActivateRabbitListeners()).willReturn(true);
given(mockConfigurationService.getAllRabbitSimpleMessageListenerContainers()).willReturn(Arrays.asList(mockSimpleMessageListenerContainer));
given(mockSimpleMessageListenerContainer.isActive()).willReturn(false);
//When
classUnderTest.handleRabbitListenerToggle();
Assert.assertThat(true, is(true));
}
}
The tests won't run as I receive a NullPointerException on given(mockSimpleMessageListenerContainer.isActive()).willReturn(false);:
java.lang.NullPointerException at
org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.isActive(AbstractMessageListenerContainer.java:1271)
at
com.cp.order.listener.SpringEventsListenersTests.testToggleTrue(SpringEventsListenersTests.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363) at
org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at
org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at
org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at
org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at
com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at
com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at
com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at
com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
I will also need to assert that .shutdown or .start were called on the container, so it needs to be mocked.
Mockito can't mock final methods (isActive() is final).
You could use reflection (e.g. DirectFieldAccessor) to check the active field instead.
That said, mocking the listener container is rather unusual; it is a complex piece of code; perhaps you could explain exactly what you are trying to test?

Unable to mock Mono object

I have been writing unit tests for Spring reactive app. I am trying to stub method response which returns Mono. I tried with samples on the net. But it is giving Null pointer exception. If we can't stub Mono types with Mockito , Please suggest me alternative way.
Complete code is available in below repository
https://github.com/NarayanaBojja/example-service
public Mono<Person> getName() {
Mono<Person> nameMono = name();
return nameMono.flatMap(per -> Mono.just(per)).onErrorResume(error -> {
return Mono.error(new RuntimeException("Name not found"));
});
}
public Mono<Person> name() {
Person person = new Person();
person.setName("Narayana");
return Mono.just(person);
}
Unit test case for the above code is
#RunWith(SpringRunner.class)
#SpringBootTest
public class DemoApplicationTests {
#Autowired
private ExampleService exampleService;
#Test
public void getNameTest() {
Person person = new Person();
person.setName("Narayana");
Mono<Person> nameMono = Mono.just(person);
given(this.exampleService.name()).willReturn(nameMono);
StepVerifier.create(exampleService.getName()).expectNext(person).verifyComplete();
}
}
I am getting below Exception
java.lang.NullPointerException
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:801)
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:772)
at reactor.test.DefaultStepVerifierBuilder.verifyComplete(DefaultStepVerifierBuilder.java:644)
at com.example.demo.DemoApplicationTests.getNameTest(DemoApplicationTests.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
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:325)
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$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)

Spring RestTemplate HTTPs service call org.springframework.web.client.ResourceAccessException: I/O error on POST request

I have to test Rest service. When I am trying with postman or curl utility it is working fine. But when I execute it using Spring RestTemplate I am getting below error. Any idea what's wrong? I am using spring boot 1,5, Spring 4, SPring STS
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://uat.pci.api.testconsumer.com/digital/dpu/charges/bankverification/v1": Software caused connection abort: recv failed; nested exception is java.net.SocketException: Software caused connection abort: recv failed
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:673)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:620)
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:414)
at com.testconsumer.consumer.workflow.integration.service.BankVerificationService.verifyBankDetails(BankVerificationService.java:113)
at com.testconsumer.consumer.workflow.integration.bankverification.BankVerificationTest.testBankVerification(BankVerificationTest.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
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:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
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:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:152)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
at sun.security.ssl.InputRecord.read(InputRecord.java:480)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:78)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.http.client.BufferingClientHttpRequestWrapper.executeInternal(BufferingClientHttpRequestWrapper.java:56)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:99)
at com.testconsumer.consumer.workflow.integration.config.RestResponseLogger.intercept(RestResponseLogger.java:26)
at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:86)
at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:70)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:659)
... 33 more
Code
#Bean
public SimpleClientHttpRequestFactory clientHttpRequestFactory() {
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(connectiontimeout);
clientHttpRequestFactory.setReadTimeout(readtimeout);
return clientHttpRequestFactory;
}
#Bean(name = "bankSerivcerestTemplate")
RestTemplate bankSerivcerestTemplate(SimpleClientHttpRequestFactory clientHttpRequestFactory) {
ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(clientHttpRequestFactory);
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.getInterceptors().add(new RestResponseLogger());
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
#Override
public boolean hasError(ClientHttpResponse response) throws IOException {
try {
return super.hasError(response);
} catch (Exception e) {
logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
return true;
}
}
#Override
public void handleError(ClientHttpResponse response) throws IOException {
try {
super.handleError(response);
} catch (Exception e) {
logger.error("Exception [" + e.getMessage() + "] occurred while trying to send the request", e);
throw e;
}
}
});
return restTemplate;
}
public ResponseEntity<ObjectNode> verifyBankDetails(RestRequest request){
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
//Headers
Map<String, Object> params = new HashMap<>();
//Params
HttpEntity<Object> httpEntity = new HttpEntity<Object>(params, headers);
ResponseEntity<ObjectNode> response = restTemplate.postForEntity(url, httpEntity, ObjectNode.class);
JsonNode root = objectMapper.valueToTree(response.getBody());
//Parse response
return response;
}
This generally happens when Server is waiting for the response from some other process e.g. client request has timed out at Server end.Server is complaining it's fine and the client has closed the TCP connection may be due to timeout or any RuntimeException at the client end.In your case, check if the endpoint has any issues with processing the request due to any exceptions or database issues.
You are receiving this error which means that the client is not responding :
Check your logs to verify that for the request through the rest template the request headers are correctly present and that you are not missing any parameters.

Spring REST Docs getting started

Following the REST Docs getting started tutorial I unfortunately receive the following error:
java.lang.IllegalArgumentException: WebApplicationContext is required
at org.springframework.util.Assert.notNull(Assert.java:115)
at org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder.<init>(DefaultMockMvcBuilder.java:52)
at org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup(MockMvcBuilders.java:47)
at f10.innovation.ApiDocumentation.setUp(ApiDocumentation.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.restdocs.RestDocumentation$1.evaluate(RestDocumentation.java:59)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
For the following code:
#Autowired
private ObjectMapper objectMapper;
#Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
#Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.alwaysDo(document("{method-name}/{step}/",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint())))
.build();
}
#Test
public void index() throws Exception {
this.mockMvc.perform(get("/").accept(MediaTypes.HAL_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("_links.business-cases", is(notNullValue())));
}
I think there a some problems regarding dependency injection. But I am unsure how to fix them.
Can you help?
Thanks a lot.
Where is the rest of your code?
java.lang.IllegalArgumentException: WebApplicationContext is required
This means you are not creating a web application context, so you need to configure this either in the web.xml or via a java configuration.
With java it's something like this:
#Configuration
public class HelloWorldConfig {
#Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
With XML and annotations, you have an XML file that your servlet loads, like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>
See here for the Spring docs:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html

Spring cache with Redis: NullPointerException

When I added #Cacheable annotation to my service method and executed it, I got following error:
java.lang.ExceptionInInitializerError
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:252)
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:58)
at org.springframework.data.redis.core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:128)
at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:91)
at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:78)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:178)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:153)
at org.springframework.data.redis.cache.RedisCache.get(RedisCache.java:104)
at org.springframework.data.redis.cache.RedisCache.get(RedisCache.java:90)
at org.springframework.cache.interceptor.AbstractCacheInvoker.doGet(AbstractCacheInvoker.java:68)
at org.springframework.cache.interceptor.CacheAspectSupport.findInCaches(CacheAspectSupport.java:461)
at org.springframework.cache.interceptor.CacheAspectSupport.findCachedItem(CacheAspectSupport.java:432)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:333)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:299)
at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy33.findMember(Unknown Source)
at com.fh.taolijie.test.dao.mapper.AccountServiceTest.testFind(AccountServiceTest.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.NullPointerException
at org.springframework.util.ReflectionUtils.makeAccessible(ReflectionUtils.java:443)
at org.springframework.data.redis.connection.jedis.JedisConnection.<clinit>(JedisConnection.java:108)
... 51 more
My configuration bean:
#Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
connectionFactory.afterPropertiesSet();
return connectionFactory;
}
#Bean
public RedisTemplate<String, MemberModel> redisTemplate() {
RedisTemplate<String, MemberModel> template = new RedisTemplate<>();
template.setConnectionFactory(this.jedisConnectionFactory);
template.afterPropertiesSet();
return template;
}
#Bean
public CacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
redisCacheManager.afterPropertiesSet();
return redisCacheManager;
}
Method that needs cache:
#Override
#Transactional(readOnly = true)
#Cacheable(value = "memberCache", key = "#username")
public MemberModel findMember(String username, boolean isWired) {
MemberModel mem = memMapper.selectByUsername(username);
CheckUtils.nullCheck(mem);
return mem;
}
Everything looks like normal. I can't tell what's wrong here..
This could be due to version compatibility between jedis and spring-data.
Saw this - Spring Data Redis 1.5.0 seems to be compatible with Jedis 2.6.2
Cannot get connection for redisTemplate for Spring data redis

Resources