Skip to content

Blog

Polya's Problem Solving Techniques

In 1945 George Polya published the book How To Solve It which quickly became his most prized publication. It sold over one million copies and has been translated into 17 languages. In this book he identifies four basic principles of problem solving.

Read more →

March 12, 2014

Create Integration Test with Spring

Assume you want to create a integration test for UserDao class which has CRUD methods e.g find, save, update, delete. Please note that for integration test: we are testing with other system like db so, we may require populate example data before test. the test method name should say that we are expecting the actual return value or save successfully, NOT invoke or interaction with some method shouldReturnNewUserWhenCreateNewUserOnSave() –> OK shouldInvokeSaveMehtodWhenUserIsNotNullOnSave() –> NOT @Repository("userDao") public class UserDaoImpl implements UserDao { User find(PK id) {...} User save(User object) {...} boolean delete(PK id) {...} } Create new class name UserDaoIntegrationTest with annotations as below @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext-dao-test.xml") @Transactional public class UserDaoIntegrationTest { ... } Inject class you want to test @Autowired private UserDao userDao; Crete test method @Test public void shoudXXX() { ... } Verify actual return value assertThat(user.getUserName(), equalTo("user1")); Method Template @Test public void should<Expecting>When<Criteria>On<MehtodName> { // Given Populate require arguments for testing method. // When Invoke method you want to test with actual value. // Then Check return value from the method. } Example @Test public void shouldReturnUserOnFindByKey() throws Exception { // Given // When final User user = this.userDao.find(1L); // Then assertThat(user.getUserName(), equalTo("user1")); } @Test public void shouldCreateNewUserOnSave() throws Exception { // Given final User newUser = User.getDefaultObject(); newUser.setReferenceType(ReferenceType.MYKAD); newUser.setUserName("abc"); newUser.setPassword("password"); newUser.setName("name"); newUser.setEmail("[email protected]"); newUser.setUserStatus(UserStatus.ACTIVE); newUser.setCreatedBy("admin"); newUser.setLastModifiedBy("admin"); // When final User createdUser = this.userDao.save(newUser); // Then final User foundUser = this.userDao.find(createdUser.getId()); assertThat(foundUser.getUserName(), equalTo("abc")); assertThat(foundUser.getPassword(), equalTo("password")); assertThat(foundUser.getEmail(), equalTo("[email protected]")); assertThat(foundUser.getCreatedBy(), equalTo("admin")); assertThat(foundUser.getLastModifiedBy(), equalTo("admin")); }

Read more →

March 5, 2014

Create Unit Test with Mockito

Assume you want to create a unit test for UserService class, getUserByUserName(String username) method. @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public User getUserByUserName(String username) { ... userDao.getUserByName(username); ... } } Create new class name UserServiceImplTest public class UserServiceImplTest { ... } Inject class you want to test @InjectMocks private UserServiceImpl userService; Mock related objects @Mock private UserDao userDaoMock; Setup annotation support @Before public void setup() { initMocks(this); } Create test method @Test public void shoudXXX() { } Verify expectation verify(userService).getUserById("admin"); assertThat(true, equalTo(true)); Static import required classes import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; Method Template @Test public void should<Expecting>When<Criteria>On<MehtodName> { // Given Declare your mock object and expectation. // When Invoke method you want to test. // Then Verify method invocation. Check return value from the method. } Example @Test public void shouldReturnUserWhenUserNameIsNotNullOnGetUserByUserName { // Given User userMock = mock(User.class); when(userDaoMock.getByUserName("admin")).thenReturn(userMock); // When User returnUser = userService.getUserByUserName("admin"); // Then assertThat(returnUser, equalTo(userMock)); }

Read more →

March 3, 2014

Pass function as argument in Java

This is an example of passing function as argument in java. It kind of ugly but it can solve my duplicate code problem as below: Before public class BinaryTest { public static void main(String[] args) { byte[] bs = "gailo".getBytes(); System.out.println("oct: " + toOct(bs)); System.out.println("binary: " + toBin(bs)); System.out.println("hex: " + toHex(bs)); } private static String toOct(byte[] bs) { StringBuilder sb = new StringBuilder(); for (byte b : bs) { sb.append(b); sb.append(" "); } return sb.toString(); } private static String toBin(byte[] bs) { StringBuilder sb = new StringBuilder(); for (byte b : bs) { sb.append(Integer.toBinaryString(b)); sb.append(" "); } return sb.toString(); } private static String toHex(byte[] bs) { StringBuilder sb = new StringBuilder(); for (byte b : bs) { sb.append(Integer.toHexString(b)); sb.append(" "); } return sb.toString(); } } After import com.google.common.base.Function; public class BinaryTest { public static void main(String[] args) { byte[] bs = "gailo".getBytes(); System.out.println("oct: " + toString(bs, new Function<Integer, String>() { @Override public String apply(Integer input) { return input.toString(); } })); System.out.println("binary: " + toString(bs, new Function<Integer, String>() { @Override public String apply(Integer input) { return Integer.toBinaryString(input); } })); System.out.println("hex: " + toString(bs, new Function<Integer, String>() { @Override public String apply(Integer input) { return Integer.toHexString(input); } })); } private static String toString(byte[] bs, Function<Integer, String> function) { StringBuilder sb = new StringBuilder(); for (byte b : bs) { sb.append(function.apply(new Integer(b))); sb.append(" "); } return sb.toString(); } }

Read more →

February 28, 2014

Hello Scala

Hello World! def hello = println("Hello world!") Functional style def append[A](xs: List[A], ys: List[A]): List[A] = if (xs == Nil) ys else xs.head :: append(xs.tail, ys) def map[A, B](f: A => B, xs: List[A]): List[B] = xs match { case Nil => Nil case h::t => f(h) :: map(f, t) } def increment(x: Int): Int = x + 1 Usage scala> val a = map(increment, List(1,2,3,4,5)) a: List[Int] = List(2, 3, 4, 5, 6)

Read more →

July 30, 2013