Category Archives: Java - Page 6

Testing a simple web app in Mule with JUnit

A simple JUnit test for when you just can’t remember the Mule JUnit testing syntax 😉

Mule flow
A Mule flow that takes a username as input and concatenates it with a “Hello”. The request is done by a GET call:

Flow code



    <http:listener-config 
       name="HTTP_Listener_Configuration" 
       host="0.0.0.0" 
       port="8081" 
       doc:name="HTTP Listener Configuration">
    
        <http:listener 
           config-ref="HTTP_Listener_Configuration" 
           path="/test" 
           doc:name="HTTP">
        <set-payload 
           value="#['Hello '+message.inboundProperties.'http.query.params'.username]" 
           doc:name="Set Payload">
    

Java test code:

import org.junit.Test;
import org.mule.DefaultMuleMessage;
import org.mule.api.MuleMessage;
import org.mule.api.client.MuleClient;
import org.mule.tck.junit4.FunctionalTestCase;

import junit.framework.Assert;

public class MyTests extends FunctionalTestCase {
	
	@Test
	public void testMyFlow() throws Exception {
        // Get the Mule Context
		MuleClient muleClient = muleContext.getClient();
		
        // Create an empty test Mule message
		DefaultMuleMessage message = 
                        new DefaultMuleMessage(null, muleContext);
		
        // Make a call to the tested web service
		MuleMessage responseMessage = muleClient.send(
                       "http://localhost:8081/test?username=Niklas", 
                       message
                    );
		
        // Get response as a string
		String responsePayload = responseMessage.getPayloadAsString();
		
        // Assert response
		Assert.assertEquals("Hello Niklas", responsePayload);
		
	}
	
	@Override
	protected String[] getConfigFiles() {
         // Path to the Mule configuration file that is being tested
		return new String[]{"src/main/app/helloworld.xml"};
	}

}

Tested on OSX 10.15.7, Mule 3.9.4, and JUnit 4.13

H2 Database: Missing UNIX_TIMESTAMP

So maybe you are running tests using an H2 database with your MySQL-based application, and you just got the message that the MySQL function UNIX_TIMESTAMP(value) is missing from the H2 database? No worries. With an H2 database, you can build your own UNIX_TIMESTAMP (or any other function you might need). I’m here going to show you one way to do it:

First, we need to create a class on the classpath of the application that connects to the H2 database, this is normally the application you are testing:

package h2;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class H2UserDefined {

    public static Long UNIX_TIMESTAMP(String d) throws ParseException {
        DateFormat dateFormat 
                          = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date dateresult = dateFormat.parse(d);
        return dateresult.getTime()/1000;
    }
}

Now we need to tell H2 that we have a new function to use. To do this we need some SQL to run against the H2 database:

CREATE ALIAS UNIX_TIMESTAMP FOR "h2.H2UserDefined.UNIX_TIMESTAMP";

Here we tell the H2 database that there is a new alias called UNIX_TIMESTAMP that can be used and that it is located in the package ‘h2’ with the path ‘H2UserDefines’ and a function name UNIX_TIMESTAMP. Quite simple 🙂

Tested on Play Framework 2.3.6, H2 v1.4

Spring Boot: Map JSON body with root node in @RequestBody

Say you have the following JSON:

{
  "rootNode": {
    "firstValue":"",
    "secondValue":""
  }
}

The class to use for this could look something like this:

public class MyValues {
  private String firstValue;
  private String secondValue;
  ...
}

This class will however not map directly to the JSON above via @RequestBody, and this is because the JSON contains a root node (“rootNode”)

The solution here is to wrap the MyValues class into a “root class” like this:

public class MyValuesWrapper {
  MyValues rootNode;
  ...
}

After this you should be able to parse the request body automatically with @ResponseBody like this:

 @PostMapping(value = "/myValues")
  public int postValues(@RequestBody MyValuesWrapper wrappedRequest) {
  
  // Optional: Unwrap for easier access
  MyValues request = wrappedRequest.getMyValues();
  ...

Hope this helps somebody (or me in the future 🙂 )

Tested on Spring Boot v2.3.8 and Java 11