Wednesday 31 July 2013

Mockito: Using ArgumentCaptor to capture argument values for further assertions.

Sometimes there are situations where I need to assert the arguments that are passed into a service, but that arguments are instantiated within a method that you want to test and in which case it cannot be asserted using a plain JUnit test.

With Mockito, I can use the ArgumentCaptor to captures values and assert them.

To explain this better, consider the following simple scenario in the CarSelector.java class.
In this class, I want to verify that every time the method buyRedFerrari() is invoked, which subsequently invoked the service (CarBuilderService.buildCar) method to build a car, it passes the expected instance of BuyingCriteria.
In this case, when the CarBuilderService.buildCar is called, it is passed with the argument that the car has to be RED and the model is a FERRARI.

Usage examples:


References:
Mockito
ArgumentCaptor API

Tuesday 30 July 2013

Hibernate: Using Transformers.aliasToBean(Class)

"Creates a resulttransformer that will inject aliased values into instances of Class via property methods or fields."

Usage examples:


This is a nice technic to automatically set values from a ResultSet to the CustomerDTO attributes.

The bean properties must match the columns name specified in the SQL statement, otherwise org.hibernate.PropertyNotFoundException: Could not find setter for... is thrown.
To make sure that this does not happen we can use SQLQuery.addScalar() so that the column names matches the attributes name of our CustomerDTO attributes.

Also, by using addScalar() we save the overhead of using ResultSetMetaData to map the column names to class attributes.

References:
- Hibernate - NativeSQL

Monday 29 July 2013

SQL: How to Cast an Integer to String in DB2



A CAST function can be used to convert one data type to another in DB2.
For example:
SELECT 100, LPAD(CAST(100 as VARCHAR(5)), 5, 'X') AS CONVERTED FROM SYSIBM.SYSDUMMY1;
Output
1 CONVERTED
100 XX100


In the example the LPAD function is used to show that the converted value is of type varchar and not integer.



REFERENCES:
Casting between data types