Adding manpower to a late software project makes it later
Filed under: scala — Tags: , , — Michael Glauche @ 11:01

What is scala ?

Scala is a relativ new compiled programming language that takes a lot of ideas from python, ruby and others. From the scala homepage:

Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive. Code sizes are typically reduced by a factor of two to three when compared to an equivalent Java application.

Why do we need another programming language ?

I mean, there are a wealth of different languages that created quite a buzz recently like ruby, python, c#. Why do you need scala ? For one, scala is a compliled language unlike ruby and python. The scala compliler generates java-bytecode that is compatible with the java jre.
This looks like a small feature but it is really one of the most interesting features of scala:

Seamles Integration in java

You can directly use java objects in scala and vice versa. Scala directly compiles to java .class files. You can deploy scala applications to your J2EE container. Which means if you are a java shop you can use your existing tools and servers to deploy scala applications. No need for a new application server, JBoss, websphere and others will work fine.

This is a very important point for larger companies. Changes in these companies can only happen graduately, so you can keep your existing knowledge and workers. The server administrators still only need to maintain the same application server they’ve been knowing for years. You even can continue to use your own libraries you’ve developed in java over the years. These points are very important if you want to make a successfull migration towards scala.

Why use Scala over Java ?

If scala is fully compatible with java, why use it ? Why learn a new language when the old one seems good enough ?

  • Scala corrects many of javas mistakes
    • Everything is an Object in scala
    • Type inference -> only need to declare the type on the right side of the assignment (i.e. var dummy= Map[String,Int]() )
    • True Mixins
    • Scala is both, a object oriented and a functional programming language
  • Fresh start
    • Clean Language, nothing feels like an addon (like generics for example)
    • much more compact, like no need for getters and setters
    • No semicolons

Hello World in scala

Enough of the theory. How does a typical scala program look like ?

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, world!")
  }
}

Filed under: Testing,java — Tags: , , — Michael Glauche @ 16:04

Using Selenium for web-gui tests is really nice. You can record your workflow with the excelent selenium plugin for firefox and use them to write your own test.
The only problem seems to be Drag&Drop. The senenium runner has some drag&drop methods, but they don’t seem to work in any way. But selenium offeres mouse controll where you can simulate mouse clicks not only at an absolute position, but rather relative to a dom object. So, if your dragable <div> element has ID1 and the dropzone has ID2 you could write the following in your testrunner:

   selenium.mouseDownAt("//div[@id='ID1']","10,10");
   selenium.mouseMoveAt("//div[@id='ID2']","10,10");
   selenium.mouseOver("//div[@id='ID2']");
   selenium.mouseUpAt("//div[@id='ID2']","10,10");

The important command for this is probably the mouseOver one, without that the richfaces d&d component for JSF would not work.

Filed under: guice,java — Tags: , , , — Michael Glauche @ 17:05

After getting angry at the java.util.logger once again i was thinking how to replace it with the SLF4J logger. Although Guice provides a very nice internal binding to java.util.logger, slf4j does offer a much nicer syntax.
The devil is in the detail, as allways … if you want your logger to be initialized with the current class you can’t simply inject the logger … But .. there is a nice tutorial on the guice wiki about injecting a log4j logger. SLF4J works the same.

First you need a new annotiation, like InjectLogger:

import static java.lang.annotation.ElementType.FIELD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectLogger {
}

next is a TypeListener, that listenes to org.slf4j.Logger classes with the annotiation InjectLogger:

import java.lang.reflect.Field;

import org.slf4j.Logger;

import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;

public class Slf4jTypeListener implements TypeListener {

	public <I> void hear(TypeLiteral<I> aTypeLiteral, TypeEncounter<I> aTypeEncounter) {

		for (Field field : aTypeLiteral.getRawType().getDeclaredFields()) {
			if (field.getType() == Logger.class
	            && field.isAnnotationPresent(InjectLogger.class)) {
	        	aTypeEncounter.register(new Slf4jMembersInjector<I>(field));
	        }
	      }
	}
}

Finally, you need the Slf4jMembersInjector, which does the actual injection:

import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.MembersInjector;

public class Slf4jMembersInjector<T>  implements MembersInjector<T> {
	private final Field field;
    private final Logger logger;

    Slf4jMembersInjector(Field aField) {
    	field = aField;
    	logger = LoggerFactory.getLogger(field.getDeclaringClass());
    	field.setAccessible(true);
    }

	public void injectMembers(T anArg0) {
		try {
			field.set(anArg0, logger);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}

Now you just need to bind your TypeListener inside your module class:

   bindListener(Matchers.any(), new Slf4jTypeListener());

The actual usage is simple, but instead of @Inject we need to use @InjectLogger :

    @InjectLogger Logger logger;

Filed under: Testing,java — Tags: , , , — Michael Glauche @ 16:20

What are Unit tests?

Unit tests are the lowest level of testing, they are whitebox tests, which means you know what the code does do. Unit tests are for testing methods of a class independently without relying to other classes or services.

This sounds good in theory, but can lead to many problems in real life, especially in J2EE enviroments, as the class you are testing depends on lots of other things, from a database connection to http request parameters.
This is one of the reasons why Unit Test Frameworks like JUnit are often (mis-)used as integration tests, for example by providing a database connection in your test. But with a database connection what are you testing ? Your code ? the state of the Database ? The OR-Mapper ? This would be a Black-Box test with too many unknown and out-of-scope variables, you would never know where in which part the error could be.
Thats why it is still very usefull to have unit tests, even if they seem hard and cumbersome to write.

Enter Easymock

With easymock it is possible to mock every Object that has an Interface. Mocking means that the actual implementation of the interface will be replaced with a dummy placeholder class that you can fill with behaviour. For example you could create a mock from HttpServletRequest which you could use to pass request parameters to your class. Another example would be to replace the database connection classes (DAOs) with mocks, so your test class does need a database anymore.

Lets look at an easy example:

public class User {
    public String name;
    public String password;
    public Integer active;
}
public interface UserDao {
     public User find(String name);
}

The actual implementation would connect to the database and fetch the User Object with the matching name.
Now, lets think we would want to test an UserService, which would use the dao to locate an user, test if the user is active and return
the user object or null if the user is inactive. The implementation (with a dependency injection framework like guice) would look like this:

public class UserService {
   private UserDao dao;

   @Inject
   public Userservice(UserDao tempDao)  {
      dao = tempDao;
   }

   public User logon(String name) {
       User tempUser = dao.find(name);
       if (tempUser.active > 0) return tempuser;
       return null;
   }
}

Now this implementation has a simple bug inside, what happens if the dao didn’t find the user ? How would a testcase find that bug ? A first draft could look like this:

import static org.easymock.EasyMock.*;
...
@Test
public void testUserLogon() {
   UserDao mockDao = createMock(UserDao.class);
   fred = new User(1, "Fred",1);
   joe = new User(2,"Joe",-1);
   expect(dao.load(1)).andReturn(fred);
   expect(dao.load(2)).andReturn(joe);
   replay(dao);
   // now we initialize the service with the mocked DAO Object !
   UserService serviceToTest = new UserService(dao);
   User result = serviceToTest.logon("fred");
   assertNotNull(result);
   assertSame(1,user.id);
   result = serviceToTest.logon("joe");
   assertNotNull(result);
   assertSame(2,user.id);

   result = serviceToTest.logon("Unknown");
   assertNull(result);
}

Now, with the help of AtUnit we can simlify the code a lot:

@RunWith(AtUnit.class)
@MockFramework(MockFramework.Option.EASYMOCK) // tells AtUnit to use EasyMock
@Container(Container.Option.GUICE)
public class UserServiceTest {
   @Inject @Unit UserService serviceToTest;
   @Mock UserDao dao;

   @Test
   public void testUserLogon() {
      fred = new User(1, "Fred",1);
      joe = new User(2,"Joe",-1);
      expect(dao.load(1)).andReturn(fred);
      expect(dao.load(2)).andReturn(joe);
      replay(dao);
      User result = serviceToTest.logon("fred");
      assertNotNull(result);
   }
}

Older Posts »

16 queries. 0.508 seconds. Powered by WordPress

Home