August 23, 2015

How to Set Default JVM on Ubuntu

If your system has more than one version of Java, configure which one your system uses by entering the following command in a terminal window

August 12, 2015

How to Log SQL Statements, Parameters and Cache in Hibernate?

Introduction

Current implementation of Hibernate are:

  • Hibernate 4.2 implements JPA 2.0 (EE 6)
  • Hibernate 4.3+ implements JPA 2.1 (EE 7)

Logging

Do not set logging level in persistence.xml (hibernate.show_sql, hibernate.format_sql), instead use Log4J for changing logging level.

You can put this in you src/test/resources/log4j.properties if you want more logging when writing or debugging your test cases.

Reference

August 11, 2015

What is Docker and Why is it Hot?

What is Docker?

It is the possible replacement for Virtualization.

What is the Difference between Virtualization and Docker?

Below is a good picture from https://www.docker.com/whatisdocker.

Docker Diagram Docker Diagram

So the difference between Virtualization and Docker is that everything runs locally on the same server, without the Virtualization overhead.

Example. Lets download a ready image from the Docker Hub (https://hub.docker.com/). You can either browse the Docker Hub via web browser or via command line.

Lets pick the official docker image. The first time you run a new Docker Image, it will download it and that will take a little while.

And now try it by open http://localhost:8888.

So what happened? We started a new process.

And a new tomcat process.

And for network. A new virtual bridge was created, which is basically a virtual router.

Why is Docker Better?

  • Lower licensing costs. You only need ONE license for the virtualized server for ALL its virtual guests.
  • More RAM and CPU. With Docker all process runs on the server directly. No virtualization layer that steals resources.
  • Less disks. A virtual guest is at least 20 GB and a Docker image is around 300 MB, since no duplication of OS and all its libraries are needed.

How Does Docker Work?

Docker makes use of proven mature Linux technologies:

  • CPU and RAM - cgroups. With cgroups you can restrict how much a process can use of the CPU and RAM, much like the same way CPU and RAM is handled in virtualization.
  • Disks - namespaces. With namespaces you can isolate local file system and divide it much like a network filesystem.
  • Network - virtual ethernet bridge.

Common Docker Commands

Installation on Ubuntu 14.04

Install docker.

Test the installation.

Reference

July 17, 2015

Getting Started with Mockito

Introduction

To create effective unit test, they should be fast. But also you might need to mock object out to be able to write unit tests. The most common library to use for mocking is mockito.

Example: Mock expected results


import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
...
    @Test
    public void testIterator() throws Exception {
        Iterator mock = mock(Iterator.class);
        when(mock.next()).thenReturn("Hello").thenReturn("World");
        assertThat("Hello World", is(equalTo(mock.next() + " " + mock.next())));
    }

Example: Mock expected result with input


import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
...
    @Test
    public void testArrayList() throws Exception {
        ArrayList mock = mock(ArrayList.class);
        when(mock.get(1)).thenReturn("Foo");
        assertThat("Foo", is(equalTo(mock.get(1))));
    }

Example: Mock expected results with any input


import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
...
    @Test
    public void testArrayListAny() throws Exception {
        ArrayList mock = mock(ArrayList.class);
        when(mock.get(anyInt())).thenReturn("Foo");
        assertThat("Foo", is(equalTo(mock.get(1))));
    }

Example: Mock and expect exception


import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
...
    @Test(expected = IOException.class)
    public void testOutputStream() throws Exception {
        OutputStream mock = mock(OutputStream.class);
        doThrow(new IOException()).when(mock).close();
        mock.close();
    }

Example: Mock and verify that metods were invoked


import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
...
    @Test
    public void testOutputStreamVerify() throws Exception {
        OutputStream mock = mock(OutputStream.class);
        BufferedOutputStream fos = new BufferedOutputStream(mock);
        fos.close();
        verify(mock).close();
    }

Using Hamcrest with JUnit 4

Introduction

The latest JUnit 4 comes with a transitive dependency of hamcrest. What hamcrest brings to the table is to increase the readability of the test code. This is important because codes are often more read than written.

Example


@Test
public void testEqualTo() throws Exception {
    assertThat(Foo.hello(), is(equalTo("Hello World")));
}

Core

The starting point is org.junit.Assert.assertThat(T actual, Matcher matcher) and the matcher methods in org.hamcrest.CoreMatchers.*:

  • allOf()
  • any()
  • anyOf()
  • anything()
  • describedAs()
  • equalTo()
  • instanceOf()
  • is()
  • not()
  • notNullValue()
  • nullValue()
  • sameInstance()

allOf()

allOf() is a simple assertion that just says all of the matcher arguments must be true.


@Test
public void testAllOf() throws Exception {
    assertThat(Foo.hello(), is(allOf(notNullValue(), instanceOf(String.class), equalTo("Hello World"))));
}

any()

This matcher just checks that the actual result is a class of a certain type.


@Test
public void testAny() throws Exception {
    assertThat(Foo.hello(), is(any(String.class)));
}

anyOf()

If any of the matchers are true this assertion will pass.


@Test
public void testAnyOf() throws Exception {
    assertThat(Foo.hello(), is(anyOf(nullValue(), instanceOf(String.class), equalTo("Goodbye"))));
}

anything()

This matcher will always evaluates to true.

describedAs()

This allows you to override the default description for a matcher.

equalTo()

See above.

instanceOf()

Checks that you have an instance of a particular type.

is()

See above.

not()

Just reverses the outcome of a matcher.


@Test
public void testNot() throws Exception {
    assertThat(Foo.hello(), is(not("Bar")));
}

notNullValue()

Simply does a null check

nullValue()

Assert a null value.

sameInstance()

Assert two Objects are ==, i.e. NOT equals()


@Test
public void testSameInstance() throws Exception {
    assertThat(2 + 2, is(sameInstance(4)));
    assertThat(new Integer(2 + 2), is(not(sameInstance(new Integer(4)))));
}

JUnit testing CDI and EJB with Mockito, OpenEJB and Arquillian

Introduction

Unit testing EE have previously been hard, but since EE 6 and onward the EE specification has been improved on the test front.

Since EE 6 the following has been added:

  • javax.ejb.embeddable.EJBContainer – A standardized test container for EJB.
  • Portable JNDISyntax – Now all EE container must conform to the same JNDI registration and lookup name spaces. Before EE 6, there was no name standard and each EE container had each different name standard.

Do we need CDI and EJB injection for unit testing?

The general rule of thumb is to make unit tests fast, because if they are not, people will starts to disable test cases. And this will make unit tests contra productive.

Loading a CDI or EJB container takes time. Which is also true for Spring Application Context. So try to write your unit test without the need to load some kind of container.

JPA and JDBC can be tested with standard Java SE

See http://magnus-k-karlsson.blogspot.se/2015/02/hibernate-best-practise-jpa-20-and.html.

Logic and EJB can be tested with Mockito

When testing logic or EJB there is in most cases no need to create a EJB context. Try to use mockito, to mock your surroundings.

EJB Container Unit Testing

In some cases there is actually a need to create an EJB context. The two most common solutions are:

  • OpenEJB
  • Arquillian

OpenEJB

Pros:

  • Is faster to start and stop than Arquillian
  • More easier to learn
  • Easy to use maven dependency

Cons:

  • Only support standard EE (which is also a pro, since then you know your code will run in any EE container.).
  • Does not support mere CDI, must use first an EJB to test pure CDI functionality. Can put EJB in test directory.

See

Arquillian

Pros:

  • Can test EE container specific code.
  • Support test of pure CDI code.

Cons:

  • Is slower than OpenEJB.
  • Its maven dependencies are long and complex.
  • Is harder to learn compared with OpenEJB.

See: