Wednesday, September 4, 2013

Moving blog to wordpress

This is the end, at least here on blogger.com :)

I have created a "new" blog over at wordpress - so get your ... over to wordpress and have a look at the new blog: https://skrymerdev.wordpress.com/

Sunday, October 2, 2011

Mocking with PowerMock and Mockito

This post is a short introduction to mocking using two of my favorite mocking frameworks, namely PowerMock and Mockito.

PowerMock is a framework designed to make testing/mocking of badly written code possible, for instance mocking static method calls.

Mockito is a mocking framework that allows you to easily create mocks and, if you want to, verify that the correct behavior was carried out.

Let's start with a small example that demonstrates why mocking is necessary, if we want to create "real" unit-tests. Imagine that we are going to implement a unit-test for an method with the following signature String getPersonInfo() which resides inside a PersonService class and the PersonService relies on a  PersonDAO, a PersonProperty and a PersonWebservice class. In order to implement a "real" unit test, for the aforementioned method, it's nessesary to make sure that the test can run in isolation, which means that mocking out PersonService dependencies should be done - in this case the DAO, PersonProperty and Webservice classes.

1. create a test - in this example JUnit is being used
public class PersonTest {
   @Test
   public void testPersonService_getDetailsForKnownPerson_returnsDetailsForPerson(){
      
   }
}
2. Create mocks for PersonServices dependencies.

The way to create mocks with Mockito is to call Mockito.mock() (you can use import static org.mockito.Mockito.*;), which takes as argument the class that is to be mocked. For instance if we want to mock the PersonDAO, we would write something like this: PersonDAO mockPersonDAO = Mockito.mock(PersonDAO.class); This returns a nice mock (all mocks in Mockito are nice) that will return default values for all methods. As mentioned earlier, PersonService relies on a PersonProperty class that for some reason is implemented using static methods, which PersonService uses - Just to make it absolutely clear, don't do this at home kids. This is were PowerMock comes into the play, because it allows us to mock static methods. The test, that are using PowerMock, should use PowerMockRunner with the @RunWirth annotation. Furthermore PowerMock requires you to specify the class, which contains the static methods, to be specified using @PrepareForTest. So our test now looks like this:
@RunWith(PowerMockRunner.class)
@PrepareForTest({PersonProperty.class})
public class PersonTest {
   @Test
   public void testPersonService_getDetailsForKnownPerson_returnsDetailsForPerson(){
      
   }
}
After setting up powermock, we are going to mock PersonService's dependencies as follows:
public class PersonTest
   ...
  
   private PersonDAO mockPersonDAO;
   private PersonWebservice mockPersonWebservice;
   private PersonServiceImpl sut;
  
   @Before
   public void setUp(){
      initializeMocks();
    
      sut = new PersonServiceImpl(); 
      sut.setDao(mockPersonDAO);
      sut.setWebservice(mockPersonWebservice);
   }

   private void initializeMocks(){
      mockPersonDAO = mock(PersonDAO.class);
      mockPersonWebservice = mock(PersonWebservice.class);
      PowerMockito.mockStatic(PersonProperty.class);
   }

   ...
}
As you can see from the code it's pretty straightforward to set up the mocks - just use mock() for Mockito and mockStatic() for Powermock.

3. Set up mock behavior/expectations and verify

First the code:
@RunWith(PowerMockRunner.class)
@PrepareForTest({PersonProperty.class})
public class PersonTest {

   ...
  
   @Test
   public void testPersonService_getDetailsForKnownPerson_returnsDetailsForPerson(){
     Integer personId = 1;
     Person person = new Person();
     String wsCallResult = "Person info : blah";
     String propertyName = "address";
     String address = "44 Taumata road Auckland";
    
     //Set up mock behavior
     when(mockPersonDAO.getMeAPerson(personId)).thenReturn(person);
     when(mockPersonWebservice.getMeSomePersonInfo(person)).thenReturn(wsCallResult);
     when(PersonProperty.getProp(propertyName)).thenReturn(address);
    
     Assert.assertEquals(wsCallResult + address, sut.getPersonInformation(personId));

     //Verify mock behavior - optional 
     verify(mockPersonDAO, atLeastOnce()).getMeAPerson(personId);
     verify(mockPersonWebservice, atLeastOnce()).getMeSomePersonInfo(person);
   }

   ...
}
Mockito comes with a DSL (Domain Specific Language) that allows you to quickly set up mock behavior, like: when(someObject.someMethod()).thenReturn(someReturnValue); for more examples go to Mockito WIKI. After setting up the behavior, you might want to verify (optional), that the correct behavior was carried out. This is done by calling verify() after the SUT is executed.

Powermock comes with implementations for EasyMock or Mockito (for now), which uses the underlying concepts of the particular framework - this allows you to use your existing knowledge of a particular framework.

Monday, September 19, 2011

Howto get proxied object for dependency injection

If you need to get the proxied object, use this code:

protected ‹T› T getTargetObject(Object proxy, Class‹T› targetClass) throws Exception {
   if (AopUtils.isJdkDynamicProxy(proxy)) {
      return (T) ((Advised)proxy).getTargetSource().getTarget();
   } else {
      return (T) proxy; 
   }
}
Code is taken from this blogpost http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring-proxy/

Tuesday, September 13, 2011

Ruby stuff

A collection of Ruby gotchas  

Using gems behind a proxy 
append -p http://your-proxy-server-name:your-proxy-server-port after any install or update commands 

or 


add export http_proxy=http://username:password@your.proxy.com:80 to your /etc/bash.bashrc file  


Getting a no such file to load -- mkmf error 
run sudo apt-get install build-essential libopenssl-$RUBY_VERSION-dev

Monday, June 13, 2011

Java Generics

Now for something completely different...

Java 5 introduced the notion of generics, which aim was to remove some of the problems surrounding casting from a unspecified object to a concrete one. This problem is especially noticeable when working with collections of unspecified objects. Let's try with a small example to illustrate the problem:

//In some class maybe a cheese factory 
public void doSomethingWithCheese(Collection cheeses){
   Iterator cheeseIterator = cheeses.iterator();
 
   while(cheeseIterator.hasNext()){
      Cheese currentCheese = (Cheese)cheeseIterator.next();
      currentCheese.cheeseBehavior();
   }
}

class Cheese {
   public void cheeseBehavior(){}
}

class Animal {}

//Some code
Collection cheeses = new LinkedList();
cheeses.add(new Cheese());
cheeses.add(new Animal());

//This call causes a classCastException because we have added an animal to the list of cheeses, and just so you know it, animals and cheeses doesn't mix well  
cheeseFactory.doSomethingWithCheese(cheeses);
The main problem with this code is that we have introduced an error which can only be detected at runtime, the compiler dosen't check your code to see if you are an idiot and mixes animals with cheeses.

Now let's rewrite the solution using generics.

public void doSomethingWithCheese(Collection cheeses){
   for(Cheese currentCheese : cheeses){
      currentCheese.cheeseBehavior();
   }
}

//Some code
Collection cheeses = new LinkedList();
cheeses.add(new Cheese());
cheeses.add(new Animal());


Now that we are using generics the the adding of an animal to the list of cheeses, is no longer possible and will result in a compile-time error.

Furthermore, when using generics it's possible to use the new foreach loop, instead of iterating through the Collection using a iterator.

Special concerns using generics:

Inheritance

use <? extends parrent >

You might think that Collection<Object> could contain any class that inherits from Object (in java all objects inherits from Object), this is not so. If you want a Collection that can contain any given object, you should use <?&gt.

When using <?> or <? extends>, it's only possible to add objects as long as you are in the same scope as to where the collection was first initialized.

Wednesday, June 8, 2011

Annotations in Java

After many years in the dark, I finally pulled myself together and started exploring this "new" feature called Annotations or meta-programming.

First things first - how to define an annotation.

The people behind Java is like the people behind the Porche 911 sports-car, incredibly lazy. Instead of coming up with a selfdescribing keyword, like Annotation, they just added a @ in front of the already known Interface keyword. So if you want to define your own Annotation you simply write this in your text-editor:

public @interface MyAnnotation  {} 
Now lets use our spanking new and incredibly awesome annotation on a new class:
@MyAnnotation
class MyClass {

}
It's that easy, just add @MyAnnotation in front of the class definition. It's also possible to use annotations on methods, which I'll demonstrate later on.

Next - adding data members to your annotation.

You could just use your annotation as flags, for instance you could create a Serializable Annotation and use this instead of the old Serializable Interface, like so:
public @interface Serializable {

}

@Serializable
public class SerializableClass {

}
This is all fine and dandy, but the purpose of annotations is to make metaprogramming possible, or at least easier. For that to work, we need to be able to define some data that goes along with our annotations. You define the data by adding one or more declarations, using this syntax: datatype nameOfMetadData followed by () and a default value using the default keyword with the desired value behind it. Here are some examples:
public @interface MyAnnotation {
int someID();
String someMetaDataAsString();
double someDoubleMetaDataWithDefaultValue() default 1234;
}

public @interface MySecondAnnotaion {
String value();
}
Annotations are only allowed to return: primitive types, Strings, Enums and arrays which contains the preceding types


It's important to remember, that annotations should only be used to describe things about a object that is outside or irrelevant to the business domain, that the object is part of. For instance, imagine a Person object that is annotated with a PersonDetail annotation, that describes stuff like the persons name, address and so on. Theses "info" are not metadata and are relevant to the domain, and should therefore be members of the object. Annotations should be used to describe stuff like how to map a given object to a database table (JPA annotations), or how a service might need transaction-handling, which are then inspected by some application framework.

If you need to read annotations programmatically take a look at JSR-269 http://www.jcp.org/en/jsr/detail?id=269

Tuesday, February 15, 2011

Guice

This is just some scribblings on Google Guice, which came together while trying to grasp the workings of the framework.

My reason for understanding the framework, comes from my desire to use DI in android development and in my search for a framework I came across RoboGuice which are a DI framework specifically made for the android platform. RoboGuice builds on Guice and therefore I had to refresh my Guice skills.

Check the RoboGuice website here: http://code.google.com/p/roboguice/

There are two main concepts in Guice, modules and injectors.

Modules are the place where object graphs are defined, this is done by extending the AbstractModule class and overriding the configure() method. AbstractModule contains methods that let's you define how objects are composed, like the example below, were a Service interface is binded to a specific implementation. The injection itself is done using the @Inject annotation like shown below.

Bindings:

public class DependecyModule extends AbstractModule {

@Override
protected void configure() {
bind(SomeService.class).to(SomeServiceImpl.class);
bind(SomeDao.class).to(SomeDaoImpl.class);

}
}

Injection:
public class Application {
private SomeService someService;
private SomeDao someDao;

@Inject
public Application(SomeService someService, SomeDao someDao){
this.someService = someService;
this.someDao = someDao;
}

public void work(){
someService.doServiceStuff();
someDao.persistSomething(new Integer("1234"));
}
...
}

To get the configured objects you use the Injector class that generates the desired object with all the dependencies injected into the returned object.

Injector use:
public static void main(String[] args) {
Injector injector = Guice.createInjector(new DependecyModule());

Application worker = injector.getInstance(Application.class);

worker.doSomeOrchestration();
}


It's that easy, go and get yourself guiced up!!

Wednesday, January 19, 2011

Howto count chars in a String

This code snippet demonstrates a simple way to count the number of occurrences of a specific char:


public static int countNumberOfCharsInString(Char c, String s){
String regex = "[^" + c + "]";

return s.replaceAll(regex, "").length();
}
The regular expression matches on the char given, which results in a String, generated from the call to replaceAll, that only contains the specified char.
The call to length therefore results in the number chars in the given String.

Wednesday, December 1, 2010

Using Enums in Spring XML config

Sometimes you need to initialize a bean using an enum. This can be achieved using the Util namespace in your XML config file as follows:

Some Java code:


Enum Weapon {
BATTLE_AXE("battle axe", 23),
LONG_BOW("longbow", 35),
BROAD_SWORD("broadsword", 25);

private String name;
private int damage;

private Weapon(String name, int damage){
this.name = name;
this.damage = damage;
}
}

public class Warrior{
private Weapon weapon;

public Warrior(Weapon weapon){
this.weapon = weapon;
}
...
}
Bean config:











Tuesday, November 23, 2010

How to use TableModel in Swing

This is a short tutorial on how to use Table models.

Simple JTable that contains person data

The first step is to create the Table Model, this can be done implementing the TableModel interface or extending AbstractTableModel. AbstractTableModel has already implemented some of the basic functionality i.e. event handling, therefore we will use this as the basis for our model. AbstractTableModel contains abstract methods that needs to be implemented in order for the JTable to work correctly - the methods annoted with @Override


public class Person{
private String firstName, lastName;

public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}

//getters
}

public class PersonTableModel extends AbstractTableModel {
private static String[] COLUMN_NAMES = {"First name", "Last name"};

private List<Person> persons;

public PersonTableModel(List<Person> persons){
this.persons = persons;
}

@Override
public int getRowCount() {
return persons.size();
}

@Override
public int getColumnCount() {
return 2;
}

@Override
public String getColumnName(int column) {
return COLUMN_NAMES[column];
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person person = persons.get(rowIndex);
String rowText = "";

switch (columnIndex) {
case 0: rowText = person.getFirstName(); break;
case 1: rowText = person.getlastName(); break;
}

return rowText;
}
}