Posts

Showing posts from September, 2017

RestTemplate Custom Interceptors

Spring Framework provides a very handy Http connection class specialized on REST communication named RestTemplate. The RestTemplate has a wealth of REST call methods that can be easily used to quickly invoke external / remote REST API endpoints with no mess of opening and closing sockets, or even marshal and unmarshaling java objects. However such ease of use comes with a caveat, whenever we need greater control with the connection, or the marshal and unmarshal process of java objects we can't do so easily as when we are using HttpConnection class. Nevertheless, one way we can gain some control to the Request and Response is through ClientHttpRequestInterceptor interface. When registered to the RestTemplate object, this interface grants us access to the Request object, request body data and also Response object. The example below shows how we can utilize ClientHttpRequestInterceptor interface to log Request and Response during a typical communication with external API: im

Mocking JNDI calls for Unit Test

Mocking JNDI calls for Unit Test Sometimes, on the rarer cases the properties data that usually drive a server based application resides in the JNDI calls instead of something.properties file. In such scenario, mocking the JNDI calls using Mockito or Powermock are inherently difficult. Luckily the Spring Framework provides a way to "mock" the context by using SimpleNamngContextBuilder. By declaring the JNDI calls in a static method (because the Builder needs to be activated before any other autowiring could take place): @BeforeClass     public static void oneTimeSetUp() throws Exception {         SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();                 builder.bind("sampleJndiKey", "sampleJndiiValue");         builder.activate();     } Here's a full sample: @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration public class TestIT {     @Autowired         Environment env

Sniffing Request and Response on Wiremock

Sniffing Request and Response on Wiremock Often we use Wiremock on our test classes without knowing how the entire request or response looks like, well, mostly the requests since we can construct the response body from plain string. For that apparently Wiremock has a nice little request listener that can be utilised to print out all requests received by the Wiremock port: Syntax:   @Rule   WireMockRule wmr = new WireMockRule(8888);   @Before   public void setUp() {     wmr.addMockServiceRequestListener(new RequestListener() {       @Override       public void requestReceived(Request req, Response resp) {         System.out.println("URL: " + req.getAbsoluteUrl());         System.out.println("Req Body: " + req.getBodyAsString());         System.out.println("Resp Code: " + resp.getStatus());         System.out.println("Resp Body: " + resp.getBodyAsString());       }     });   } or the Java 8 way: