5 minutes with – Spring Junit

Ok, you’ve done the best code you’ve ever written in your life. Well done but, even the best code written in this world, should have a test case inside.

This simple rule is the basic for code maintenance over the time. Unfortunately, it’s not common enough as I wish it would be.

In this post I’ll try to break this bad habit showing how build a easy and quickly test.

Let’s start. My example starts from Spring Web Services example at my previous post. Take a look at it to understand the easy components.

package it.samplewebservicespring.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import it.samplewebservicespring.bean.Speak;
import it.samplewebservicespring.service.HelloService;
import it.samplewebservicespring.service.Language;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = { "/application-context.xml"})
public class HelloTest {

    private HelloService hello = null;

     * Tests message.
    public void testMessage() {  
        assertNotNull("Constructor hello instance is null.", hello);
        Speak message = new Speak();
        String expectedMessage = "Ciao";
        assertEquals("Message should be '" + expectedMessage + "'.", expectedMessage, hello.speakHello(message).getOriginalMessage());

Take a look at @RunWith(SpringJUnit4ClassRunner.class). It is used to declare the class as Unit test class.

Easily, we’ve injected the HelloServiceImpl object defined into the context configuration.

At method testMessage we have two tests. The first is to check the injected object and the second is to test the language response message.

If everything is ok, you’ll see a green bar into eclipse, like this:

The package org.springframework.test is inside spring-test-X.RELEASE.jar.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s