Assert JSON

JSONassert is a project to “Write JSON unit tests in less code. Great for testing REST interfaces.” The following is maven dependency of JSONassert:

<dependency>
 <groupId>org.skyscreamer</groupId>
 <artifactId>jsonassert</artifactId>
 <version>1.3.0</version>
</dependency>

To test whether 2 JSON objects are same or not, do the following:

JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE);

NON_EXTENSIBLE is the most commonly used compare mode of 4. You can check javadoc to find out how they function.

Expose to GSON

Gson is a tool to convert between Java objects and JSON objects. Its usage with JSON is somewhat similar to the usage of JAX-B with XML (although JAX-B can also process JSON). This article will explain the basis of GSON in order to get a quick understanding of how it works for anyone who is new to GSON.

Maven Dependency

At the time this article is composed, the following GSON dependency is the latest release version.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.7</version>
</dependency>

For more information about Maven configurations, see POM Configurations.

Serialize & Deserialize

There are 2 steps for both Serialization and Deserialization with GSON: annotate the fieds, and process.

Annotation

To serialize or deserialize objects, you need first to annotate the fields of the java classes (most likely to be Entity Beans). The following code is an example of annotating field. Basically, this is all you need to do in most cases.

@Expose
private String name;

There are 2 boolean arguments you can pass in for this annotation: serialize, deserialize. By default, they are both true, means you will include this annotated field in both processes. If serialize is false, when turning java object to json, this field will be ignored. On the other hand, if deserialize is false, when turning json to java, this field will be ignored. In addition, if you set both to be false, it’s same to not annotating @Expose on this field.

If you would like to change the name of the fields in the JSON file, you can use @SerializedName. For example:

@SerializedName("n")
private String name;

The following code shows an Entity class with GSON annotations.

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
@Table(name = "student")
public class Student implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Expose
    private Long id;

    @NotNull
    @Size(min = 2, max = 25)
    @Expose
    @SerializedName("n")
    private String name;

    // getters and setters...
}

From the above code stub, you can see that only field level annotation is needed.

Processing

To process conversion between Java object and JSON object, you can do the following.

Converting from JSON to Java object:

Target targetObject = new GsonBuilder().create().fromJson(jsonBody, Target.class);

Converting from Java object to JSON:

String jsonBody = new GsonBuilder().create().toJson(targetObject);

In above code, Target is a class annotated and associated with the body of the JSON String: jsonBody. However, I omitted some middle processes of how to create a Gson instance.

GsonBuilder gb = new GsonBuilder();
Gson g = gb.create();
// then you can do g.toJson() or g.fromJson()

The GsonBuilder instance can accept some configs in order to customize the conversion.

Versioning

In order to do versioning, you can put @Since and @Until to the fields of the Java objects:

@Since(1.1)
private String newStandard;

@Until(0.9)
private String oldStandard;

To make them work, you can configure the GsonBuilder:

GsonBuilder gb = new GsonBuilder();
gb.setVersion(1.0);

Then, the Gson instance will process conversions based on the version.

First Sight of Mockito

Mockito is a mock testing tool which can help developers to do testing without completing all functions. In this article, I’ll be writing some code to show how it works. To begin with, you need to build Mockito into your project. The following maven repository is the latest release version when I’m writing this article. To build project with maven, see POM Confiurations.

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.10.19</version>
    <scope>test</scope>
</dependency>

To make life easier, you may also want to statically import the following methods:

import static org.mockito.Mockito.*;

Next, choose a class that you want to mock up:

StudentDAO studentDAO = mock(StudentDAO.class);

In the above code, since studentDAO is mocked up by Mockito, this instance becomes a puppet. You can manipulate the output (return value) of any method in StudentDAO class by monitoring the input (parameter) in order to perform a mock test. The following code shows how to register a manipulation role, and use it.

@Test //this test case tests if the logic part in that method functioning correctly
public void delete(){
    Student student1 = new Student();
    // set some properties to student1 which are meant to let it pass the logic part in StudentService().delete()
    when(studentDAO.delete(student1)).thenReturn(true); // this is how studentDAO.delete() being manipulated

    AssertTrue(new StudentService().delete(student1));
}

StudentService class stub:

// imports

public class StudentService{

    // some other variables and methods...

    StudentDAO studentDAO;

    public boolean delete(Student student){

        // perform some logic which may cause a return of false, and stop deleting the given Student

        return studentDAO.delete(student); // this studentDAO.delete() method has been interfered to return true when student1 is passed in
    }
}

Benefits of Mock Testing

Because of the ability of manipulate the return value of a method, it gives you the power to test your program based on assumptions. For example, you’ve had a class structure and method definitions, yet been implemented. The methods would return null value. Therefore, you can’t test other classes which depend on the functions that this class provides, if you just do the regular test. With mock testing, you can pretend you had those methods implemented by controlling the results. On the other hand, it also lets you to isolate the problems to what you are focusing on.

Other Commonly Used Methods

verify

To verify if a method is being called or not, you can verify it.

public static <T> T verify(T mock) // verify if a certain method is called once
public static <T> T verify(T mock, VerificationMode mode) // verify if a certain method is called certain time(s)

The above code are the method signatures of verify function. To use one of these methods, you need to mock a class, and run your test first. Then followed by verify method to check if the method is called. For example:

studentDAO = mock(StudentDAO.class);
studentService.studentDAO = studentDAO;
studentService.update();
verify(studentDAO).update();

In this example, I want to test if studentDAO.update() is called by studentService.update(). If it is called, then test passed, otherwise, test would fail.

@Mock

Instead of doing something like this:

StudentDAO studentDAO = mock(StudentDAO.class);

with @Mock annotation, you can initialize mocked classes easier:

@Mock
StudentDAO studentDAO;

@Mock
StudentService studentService;

@Mock
SomethingElse somethingElse;

Then, all you need to do is to initiate them at once:

MockitoAnnotations.initMocks(this);

doThrow

If your mocking method has a void return type, then you have to reverse the when-then order. Following code shows how to let a void method throw an exception:

doThrow(new Exception()).when(studentService).update(new Student()); // update() is a void method

Java Validation

By using EJB, validation can be processed automatically. However, this article talks about how to do it manually. I separate the whole procedure into 3 steps: Entity Bean Annotation, Processing Validation, and Unit Testing.

Entity Bean Annotation

You can tell how you want the fields of your entity beans to be validated by putting annotations on them.

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
@Table(name = "student")
public class Student implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Size(min = 2, max = 25)
    private String name;

    // getters and setters...
}

The Bold Annotations are going to be used for validating the value of name field.

Processing Validation

In your functional class, such as a Service class, you can use Validator to validate the entity bean. It will process validation for the entire instance of the Entity and return all ConstraintViolations in a Set. In order to get all the elements of the Set, you need an Iterator.

import java.util.Iterator;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

public class StudentServices {

    Validator validator; // the instance of validator is usually being injected, or passed in

    public void validate(Student student){
        Iterator<ConstraintViolation<Student>> errors = validator.validate(student).iterator();
        if (errors.hasNext()) {
            ConstraintViolation<Student> violation = errors.next();
            throw new RuntimeException(violation.getPropertyPath().toString() + ": " + violation.getMessage()); // property path is the field name of the entity where the value violates the constrain
        }
    }
}

Validator can validate an instance of the Entity by using its (entity’s) constraint.

Unit Testing

This unit test shows how Validator being created, and if all have been done correctly, the test should pass.

import static org.junit.Assert.*;

import javax.validation.Validation;
import javax.validation.Validator;

import org.junit.Before;
import org.junit.Test;

public class StudentServicesTest {

    private StudentServices studentServices;

    @Before
    public void initTestCase() {
        studentServices = new StudentServices();
        studentServices.validator = Validation.buildDefaultValidatorFactory().getValidator(); // This is how a Validator being created
    }

    @Test(expected = RuntimeExeption.class)
    public void validate() {
        studentServices.validate(new Student()); // this instance of Student entity does not have a name (name field is null), which violates the @NotNull annotation on name field
    }
}

The message of thrown RuntimeExeption will be something like “name: …” because the property path was added when it’s been throwing out.

Singleton Pattern Example

This is a thread safe, lazy load singleton example:

public class Singleton {
    private Singleton() { // make it private to prevent instantiation from outside
        // some code for the constructor
    }

    private static class InsHolder { // Once getInstance() being called, this class will be loaded (Lazy)
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return InsHolder.INSTANCE;
    }
}

The down side of the above code is you can’t throw exceptions on constructor.

Lambda Expression Examples

Original code to loop through the List<Element> elements:

for(Element e: elements){
// do something with e
}

Use of -> (in case there is no need to declare the type):

elements.forEach(e -> {
// do something with e
});

Use of :: (in case you already have a method to deal, and only deal with e):

elements.forEach(instance::method);

Note: The instance can be a reference, a new statement, or this keyword. If the method is static, the first part of :: can also be the class name.

In some other cases, there might be no parameter, or more than one parameters.

If the interface of the call parameter only needs one parameter:

void call(new Interface(){
    void execute(Object o){ // only single-method interfaces can be translated to Lambda Expression
        // some code
    }
});

It can be translated to:

call(e -> { // e represents Object o on above code stub
    // some code
    // since the return type of Interface().execute() method is void, there's no need of return statement
});

Only one line statement:

call(e -> statement);

Using method delegation:

call(instance::method);
// void method(Object o){ // if Interface().execute() demands a return, then the return type of this method must be same
//     // some code
// }

If the interface of the call parameter needs no parameter:

void call(new Interface(){
    void execute(){ // only single-method interfaces can be translated to Lambda Expression
        // some code
    }
});

It can be translated to:

call(() -> { // () is used to indicate there's no parameter
    // some code
    // since the return type of Interface().execute() method is void, there's no need of return statement
});

Only one line statement:

call(() -> statement);

Using method delegation:

call(instance::method);
// void method(){ // if Interface().execute() demands a return, then the return type of this method must be same
//     // some code
// }

If the interface of the call parameter only needs two or more parameters:

void call(new Interface(){
    void execute(Object o1, Object o2){ // only single-method interfaces can be translated to Lambda Expression
        // some code
    }
});

It can be translated to:

call((e1, e2) -> { // (e1, e2) represents o1 and o2 on above code stub
    // some code
    // since the return type of Interface().execute() method is void, there's no need of return statement
});

Only one line statement:

call((e1, e2) -> statement);

Using method delegation:

call(instance::method);
// void method(Object o1, Object o2){ // if Interface().execute() demands a return, then the return type of this method must be same
//     // some code
// }

Function interface

The only way to use lambda express without a method call is to use functional interface (with @FunctionalInterface annotation). E.g. Function interface.

@FunctionalInterface
public interface Function<T, R> {...}  // T: input type R: return/result type

An example of using Functional interface:

Function<Long, Long> square = x -> x * x;

or

Function<Long, Long> square = instance::method;
// Long method(Long x){return x*x;}

Wrong:

NoneFunctionalClass<Long, Long> square = instance::method; // can not pass compilation

An example of method level generic type usage

This example shows how to use generic type in a design pattern.
The following code will structure a process to separate logic code from routine tasks.

First, create an interface and an unimplemented method, which will be called in Executor class:

public interface Executable<T> { T execute(); }

Second, code the routine tasks, and insert the logic to be execute:

public class Executor {
    public <T> T process(Executable<T> e) {
        //pre execution. e.g.: start transaction
        T t = e.execute();
        //post execution. e.g.: commit transaction, close resource etc.
        return t;
    }
}

Finally, call the Executor to process your task, and code the business logic:

public class Caller {
    public static void main(String args[]) {
        DeterminedType t = new Executor().process(() -> {
            //code to deal with the business logic
            return result; //the type of the result returning here will determine the type of t
        });
    }
}