I'm stuck trying to run a unit test that makes a web service request. I'm mocking the proxy object of the jax-ws request in my JUnit test using EasyMock.
I have defined the bean using DI in my application-context as follows:
<bean id="mockOrderPort" name="mockOrderPort" class="org.easymock.EasyMock" factory-method="createStrictMock" >
<constructor-arg value="com.proyecti.perama.siman.replica.integration.schema.OrderPort" />
</bean>
This is the test case that is failing:
//II. Fill the authentication response will be used to mock the server calling
final AuthenticationResponse authenticationResponse = new AuthenticationResponse();
authenticationResponse.setToken(encode(TestConstants.EMPTY_TOKEN));
//III. When authentication is called, mock must return the authentication request object created earlier
expect(mockOrderPort.authentication(EasyMock.anyObject(AuthenticationRequest.class))).andReturn(authenticationResponse);
//IV. Make the mock object available for executing the test
replay(mockOrderPort);
//V. Execute the test (call to server is produced inside this method)
executeTest();
//VI. Verify mock behaviour is correct
verify(mockOrderPort);
Inside the executeTest method, there is the call to the WS using the mocked proxy object:
authenticationResponse = portToServer.authentication(authenticationRequest);
No matter what I try, but it ALWAYS tries to connect to the actual WS, raising the following exception:
authentication request has not been successful. Exception: com.sun.xml.ws.client.ClientTransportException: HTTP Transport error: java.net.ConnectException: Connection refused: connect
Why is the mock object trying to connect instead of returning the object I have created?
Thanks!
Related
I'm consuming data from a REST endpoint with in the middle of the route a proxy. I'm having CNTLM running locally (localhost:3128 ): it will authenticate for me on the corporate proxy, so I don't need to pass my credentials.
I have been unable to get my rest call to work, despite numerous attempts. For e.g., getting:
SSLException: Unrecognized SSL message
Connection handshake abruptly terminated
Connection reset
you name it, have got it
Below the simplest version of the many attempts made.
Apparently (from internet reading), that should work, but it doesn't.
How should Camel be configured, in particular camel-http ?
Notes:
The REST API I'm calling is using HTTPS but doesn't require a certificate.
The code works on my local machine when no proxy is involved. It fails on the intranet where there is a proxy
#Component
public class MyRoute extends RouteBuilder
public void configure() throws Exception {
//Tried different way to set the proxy, including inline with toD(...)
System.setProperty("https.proxyHost", "localhost");
System.setProperty("https.proxyPort", "3128");
getCamelContext().getGlobalOptions().put("http.proxyHost", "localhost");
getCamelContext().getGlobalOptions().put("https.proxyPort", "3128");
getContext().getGlobalOptions().put("https.proxyHost", "localhost");
getContext().getGlobalOptions().put("https.proxyPort", "3128");
from("timer:credentials?repeatCount=1")
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setBody(simple(jsonAuth))
.to(baseUrlApi +"/v1/auth/tokens/?bridgeEndpoint=true")
.unmarshal().json(JsonLibrary.Jackson, AuthResponseDto.class)
.setHeader("Authorization", simple("Bearer ${body.data.accessToken.token}"))
// etc..
}
}
I have Class in which I call a method from a declarative client. But for my test I don't want it to call the actual URL. Instead I want to Mock it. How can I do that as it is not a class but an Interface annotated with #Client?
Example code:- here. Please check section 4.3
In your test you can replace the http client bean with a mock. Please find a Spock snippet below.
// replace the client with a mock
#MockBean(YourClientInterface)
YourClientInterface yourClientInterface() {
return Mock(YourClientInterface)
}
// inject the mock in order to configure responses when it gets called
#Inject
YourClientInterface client
Now you can write tests and your code will run against the mock instead of the actual http client.
I have an spring advice method which logs the exception after a method (in DAO layer) throws an exception. The DB query are handled at DAO classes.
while running the code my service method (S1), which interns call DAO layer method (D1) to execute query.
test case: DB is up and code execute normally. in second run, meanwhile DB is down, and calls doesn't reach to DAO layer and exception throws (Connect excpetion) at service layer (S1) itself; hence advise not able to log the excpetion because calls is not reached to DAO.
how the jdbc connections are managed by server (tomcat)?
I have setup a Spring Integration flow configuration to send messages to an external web service and then unmarshalling the response and then doing some post processing based on the response object type.
I have the following outbound-gateway configuration:
<int:channel id="sendRequestChannel"/>
<ws:outbound-gateway request-channel="sendRequestChannel" uri="${send.ws.uri}" reply-channel="responseTransformer" >
<ws:request-handler-advice-chain>
<ref bean="retryAdviceUserUpdateWs" />
</ws:request-handler-advice-chain>
</ws:outbound-gateway>
Now, I want to test the flow and check that the correct post processing is triggered based on the response object.
Is there anyway in my integration test to mock the Endpoint response based on the message I'm sending?
Actually you should understand from which part of your flow it would be better to mock and return the desired response.
You can inject ChannelInterceptor to the sendRequestChannel with preSend which returns null, to prevent the further process and send a message with desired response to the responseTransformer.
Another powerful option is to add one more Advice to the <ws:request-handler-advice-chain> and implement it as extension of AbstractRequestHandlerAdvice.
And the last option which I see via Java code is a mock for WebServiceTemplate.sendAndReceive and inject it to the <ws:outbound-gateway>.
From other side I know that SoapUI has a tool to mock target service, so, you even don't need to do anything in Java, unless tests.
So, it up to you to choose the proper way to test you flow.
I'm hoping to save some client info (IP address, etc) to a database on session created in Spring MVC.
I created a class implementing HttpSessionListener and configured it in web.xml. However, I'm not sure where to go after that.
Would like to be able to inject a bean as well (Spring Data JPA repository).
I've seen How to get the IP address when a session is created? , however if I try to access RequestContextHolder.currentRequestAttributes() I get the following exception:
SEVERE: Session event listener threw exception
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
You can create a bean this way with Spring java config:
#Bean
#Named ("IP")
#Scope ("session")
public String ip (HttpServletRequest request) {
return request.getRemoteAddr ();
}
If all you want to do is log stuff then you should use the HttpSessionListener, please provide your source and full stack trace. Use pastebin.com if necessary.