how test a kotlin class?


TDD is a modern software development process based on creation of automatic test before write code, so modern programming can’t be called in this way without test the software. In this post i want to write something about testing software written in kotlin .

Ok, after this little presentation let’s start to write some code: in the previous post on kotlin the problem was connect to mongo db and write some data. Now i want to complicate this example and the challenge is write a class (data class) and then save it into the database.

In kotlin write a data class is very simple (can find here), my data class for this example is this:

data class Person (val name:String, val surname:String, val age:Int)

Testing this class is very simple, we can test it in the same java way: with junit!

On IntelliJ create test can be done directly from the class:

Schermata 2016-05-22 alle 21.41.20

Schermata 2016-05-22 alle 21.44.54

We can select which methods to test and the IDE create the skeleton for the test class:

Schermata 2016-05-22 alle 21.48.29

I saved this test class in a test folder to keep everything organized. It’s important to configure the test folder for the project:

Schermata 2016-05-22 alle 21.55.26

Schermata 2016-05-22 alle 21.55.44

Now, all it’s configured, and now i can test my class! Run the test class and the result is something like this:

Schermata 2016-05-22 alle 21.58.28.png

gatsby-is-already-doing-great-at-the-box-office-despite-harsh-reviews      All Green! Great!


Kotlin exercise 1: Connect to MongoDB -part 2-


In the first part of this exercise we have seen how connect to a MongoDb with Java. Now that is clear how the connection can be performed, we can try to do the same with Kotlin.
Ok, no waste other time, start coding:

import com.mongodb.BasicDBObject
import com.mongodb.MongoClient
import com.mongodb.MongoException
import java.util.*

 * Created by Claudio on 01/05/16.
 * This is a main to test mongoDB connection in kotlin

fun main(args: Array<String>) {

        val mongo = MongoClient("localhost", 27017)

        val db = mongo.getDB("testDB")

        val table = db.getCollection("person")

        //Reflection example
        val person = Person("Jon","Doe",20);

        val data = person.javaClass;

        //Insert document
        val document = BasicDBObject()
        document.put("name", "mkyong")
        document.put("age", 30)
        document.put("createdDate", Date())

        /**** Find and display ****/
        val searchQuery = BasicDBObject();
        searchQuery.put("name", "mkyong");

        val cursor = table.find(searchQuery);

        while (cursor.hasNext()) {
    catch (e: UnknownHostException) {
        e.printStackTrace ( );
    } catch (e: MongoException) {


Sorry but the kotlin code isn’t highlighted

How we see the code is similar with Java example and the output is equal:

Schermata 2016-05-04 alle 21.10.01

This code can be converted from Java code with the intellij IDE function called: “Convert java code to kotlin code”. This can be reached from the search tool or vith copy and paste of java code to kotlin file:


For exercise the “Main.kt” code is was written from scratch.

In this little exercice I learned how connect to MongoDb and how code something more difficult to “hello world” in Kotlin.

A little step for mankind, a big step for a developer!


Apache Thrift


What is Apache Thrift? Thrift is a framework. With this framework the programmers can create high-performance cross-language services.

With Thrift you can write the specifications of the contract between two or more microservices (client side and server side), and then you can generate the stub code for the right programming language.

The programming languages supported by Apache Thrift are:

AS3 C C++ C#
D Dart Delphi Erlang
Go Haskell Haxe Java
JavaScript Lua Node.js Objective-C
OCaml Perl PHP Python
Ruby Smalltalk TypeScript

The “contract”is written in IDL (Interface Definition Language). Into this file the developer specify the abstract data type. After this definition, the IDL can be compiled into source code. This step seems to be a wasting time, but is useful because the developer must consider the interface in isolation, without thoughts on code.

I think Apache Thrift is a very useful framework for this reasons:

  • The design stage of the micorservice is independent from the implementation stage
  • Is useful in heterogenic  teams: all developers can work on a project and use the preferred programming language.
  • In this way, the designer, create a contract between the services that is clear and documented.

Useful links about this argument are:


About interface event handling

When I work with user interface, if into a event handling method there is some code that not manages interface elements but implements logic, I prefer not write that code directly into the method but I create other method with the logic and then recall this method into the event handling method.
This implementation is a little bit complex and verbose than a direct implementation but is more open and reusable for the future development.
Consider this scenario and suppose to use c++ as programming language: we have a method that manage the clik on a certain button, called MyButton, on my user interface. The method for click management is MyButtonOnClick(TObject *Sender):

void MyClass::MyButtonOnClick(TObject *Sender)
   int param1 = getParam1();
   int param2 = getParam2();
   //this is the logic write directly into the event handling method
   int ret = param1 + param2;
   ResultLabel->Text = StringToInt(ret);  


In MyButtonOnClick there is a piece of code that implement addition of two params (from other interface elements or from other methods). This addition can be wrapped into other method so I can reuse that.

My implementation begin something like this:

int MyClass::AddParam(int param1,int param2)
   int ret = param1 + param2;
   return ret;   

void MyClass::MyButtonOnClick(TObject *Sender)
   int param1 = getParam1();
   int param2 = getParam2();

   int ret = AddParam(int param1,int param2);
   ResultLabel->Text = IntToString(ret);  


In this way i can reuse the AddParam Method into other methods.

The example is very simple but explain clearly the initial these.

PHP soap client example

Hi guys, today I want to focused on a simple php thing: soap client. I found this very important in my last project so I want to share with you something about this. First of all it’s important to understand how vsld describe the method that client can call. An example of vsld is the following:

<message name="UserEnabled">
   <part name="parameters" element="tns:UserEnabled">;

<xs:element name="UserEnabled">
<xs:element name="userId"type="xs:int" />

This is the description of a method interface for a generic soap server that manages some connection. In particular this method enable user at the operations on that server. Now we can implement the client for this vsdl, is very easy code:

$client = new SoapClient("http://serviceaddress/data/user.wso?wsdl");
$result = $client→UserEnabled(array('userId'=>$userId));

We can call the method exposed in the vsdl like a method of the instantiated soap client! Is very powerful!

Now, If you want to use this into a method, an example of implementation is something like this:

 * @param integer $userId
 * @return boolean
 public function UserEnabled($userId)
   $result = $this->signAction->UserEnabled(array('userId'=>(int)$userId));
   $ret = false;
   if($result->res == "OK")
     $ret = true;
   return $ret;

See you soon bye bye!

Singleton pattern java example

I found singleton design pattern a useful pattern for my applications. But, what is this design pattern?

In this pattern a single class is responsible to create an object, and you are sure that only single object is created. In this manner, this class provides a way to access its only object which can be accessed directly. No instatiate is needed.

What are the features of this type of class:

  • private costructor
  • Static instance of itself
  • Static method to get own static instance

Now, create a Singleton Class:

public class Singleton {
    private static final Singleton instance = new Singleton();
    public static Singleton getInstance() { 
       return instance; 
    public void showMessage(){
       System.out.println("Hello World!");

Now use this class into a snippet:

public class SingletonPatternDemo {
 public static void main(String[] args) {

   //illegal construct
   //Compile Time Error: The constructor SingleObject() is not visible
   //SingleObject object = new SingleObject();

   //Get the only object available
   Singleton object = Singleton.getInstance();

   //show the message

And now verify this code!