Wednesday, 17 September 2014

Mockito Tutorial -Part2 . Spring and Mockito Integration.

In the below example we use Calcuator Obect which computes the area of Rectangle using Rectangle Objects.

Frame works used

  • Spring -Dependency Injection
  • Mockito- Mocking java Obejcts
  • JUnit- Unit Test frame work.


CalculatorTestWithSpringAndMockito.java 
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

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

import com.lac.tut.mockito.Calculator;
import com.lac.tut.mockito.Rectangle;

@ContextConfiguration(locations = { "classpath:/beans.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class CalculatorTestWithSpringAndMockito {

 @Mock
 Rectangle rectangle;

 @InjectMocks
 @Autowired
 Calculator calculator;

 @Before
 public void create() {
  initMocks(this);// Initialize this mock objects
  when(rectangle.getLength()).thenReturn(10);
  when(rectangle.getBreadth()).thenReturn(40);
 }

 @Test
 public void test() {
  assertEquals(calculator.getArea(), 400);
 }

}

Explanation: In the above example the mocked rectangle object is injected into calculator object. @InjectMocks annotation of Mockito inject mocked rectangle object into calculator bean. The annotation @RunWith makes the class is runned with SpringJUnit4ClassRunner. The annotation ContextConfiguration specifies the path of spring bean definition.


Calculator.java
 
package com.lac.tut.mockito;

public class Calculator {
 private Rectangle rectangle;

 public Rectangle getRectangle() {
  return rectangle;
 }

 public void setRectangle(Rectangle rectangle) {
  this.rectangle = rectangle;
 }

 public int getArea() {
  return rectangle.getLength() * rectangle.getBreadth();
 }

}


Rectangle.java
 
package com.lac.tut.mockito;

public class Rectangle {
 public int length;
 public int breadth;

 public int getLength() {
  return length;
 }

 public void setLength(int length) {
  this.length = length;
 }

 public int getBreadth() {
  return breadth;
 }

 public void setBreadth(int breadth) {
  this.breadth = breadth;
 }

}


beans.xml
 


 
 
 
  
 
 
 
  
  
 
 



Download the source code of above tutorial at : http://www.luckyacademy.com/downloads.html




Tuesday, 16 September 2014

Mockito Tutorial -Part1


  • What is Mockito?
    • Mockito is mocking frame work for Java Objects.
  • Why do we need to Mock Objects?
    • When an unit of code depended upon object that will not be available during test or development. We can create a mock object of it.
  • What is Mock Object?
    • A mock object is a dummy implementation for an interface or a class in which you define the output of certain method calls
Lets try to Mock a object of  Math class that was not avilable during development.

Math.java
package com.lac.tut.mockito;

/**
 * Performs various Math Operations like addition,multiplication and division ..etc 
 *
 */
public class Math {
 // addition of two numbers
 public int add(int a, int b) {
  return a + b;
 }

 // Multiply two numbers
 public int mul(int a, int b) {
  return a * b;
 }

 // Division of two numbers
 public int div(int a, int b) {
  return a / b;
 }
 
 //Return a prime number
 public int primeNumber(){
  return 5;
 }
}
Explanation: The above Math class has addition,multiplication,division as functions.

MathAddTestWithOutMock.java is a unit test cases that test add method on Math Object
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;

/**
 * Test the add method of Math object
 */
public class MathAddTestWithOutMock {
 Math mathObj; 

 @Before
 /**
  * Create Math object before you use them
  */
 public void create() {
  mathObj = new Math();//create a math object
 }

 @Test
 public void test() {
  assertSame(3, mathObj.add(1, 2)); // Assert that math object return 3
 }

}

Explanation: In the above example we try to test add method. Often In the Test Driven Development we will not have Math class before we write tests around it. The approach we have to take is Mock the Math object and write the tests using Mocked object.


MathMockAddTest.java Tests the add method of Math class by mocking Math Object
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;

/**
 * Test the add method of Math object
 */
public class MathMockAddTest {
 Math mathObj; //The object that needs to mocked
 
 @Before
 /**
  * Create mock object before you use them
  */
 public void create(){
  mathObj= mock(Math.class); //Create Math mock Object
  when(mathObj.add(1, 2)).thenReturn(3); // Configure it to return 3 when arguments passed are 1,2
 }
 
 @Test
 public void test() {
  assertSame(3, mathObj.add(1,2)); //Assert that math object return 3
 }

}

Explanation: In the above code the static method mock is going to create mock object of Math class. The static method when defines the behavior of add method. (i.e) When some one called add method with arguments 1 and 2 return 3 as output. Note: Please bear in mind. MathMockAddTest is never creating a Math concrete object it is only creating Math mock object.


MathMockAddTestWithAnnotation.java Creates a mock object with Mockito Annotations
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;

import com.lac.tut.mockito.Math;

/**
* Test the add method of Math object with  Mockito annotation
*/
public class MathMockAddTestWithAnnotation {
 @Mock
 Math mathObj;
 
 @Before
 /**
  * Create mock object before you use them
  */
 public void create(){
  initMocks(this);// Initialize this mock objects
  when(mathObj.add(1, 2)).thenReturn(3); // Configure it to return 3 when arguments passed are 1,2
 }
 
 @Test
 public void test() {
  assertSame(3, mathObj.add(1,2));//Assert that math object return 3
 }

}

Explanation:In the above example @Mock annotation is used to mock Math object. The static method initMocks initializes the mock objects in current class. Rest the behavior defined is same.


MathMockMulTest.java Test the multiplication method in Math class
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.*;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;

/**
 * Test multiply function
 */
public class MathMockMulTest {
 Math mathObj;
 
 @Before
 public void create(){
  mathObj= mock(Math.class);
  when(mathObj.mul(anyInt(), eq(0))).thenReturn(0); //Multiply any number with zero. The function should return zero
 }
 
 @Test
 /**
  * Test the Multiply function in math object return zero if one of the argument is zero
  */
 public void test() {
  assertSame(mathObj.mul(1,0),0);
  assertSame(mathObj.mul(3,0),0);
 }

}

Explanation:In the above example the static method anyInt accepts any argument as input and static method eq checks that the argument is zero.


MathMockDivTestWithException test the exception returned by div method in Math class.
 
package test.com.lac.tut.mockito;

import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;

/**
 * Test division method of Math class
 */
public class MathMockDivTestWithException {
 Math mathObj;
 
 @Before
 public void create(){
  mathObj= mock(Math.class); //Create Math Object
  when(mathObj.div(anyInt(), eq(0))).thenThrow(new ArithmeticException()); // Configure it to return exception when denominator is zero
 }
 
 @Test(expected=ArithmeticException.class) //expect the method throws ArithmeticException
 public void test() {
  mathObj.div(1,0); //call the div and expect to return ArithmeticException
 }

}

Explanation: The static method thenThrow should throw exception when denominator is zero.


MathMockPrimeNumTestWhichIsAMethodWithOutParameters Test a primeNumber method that doesn't take any argument
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;

//Test a method that doesn't take any argument
public class MathMockPrimeNumTestWhichIsAMethodWithOutParameters{
 Math mathObj;
 
 @Before
 public void create(){
  mathObj= mock(Math.class); //Create Math Object
  when(mathObj.primeNumber()).thenReturn(5); // Configure it to return 5 as prime number
 }
 
 @Test
 public void test() {
  assertSame(5, mathObj.primeNumber());
 }

}
Explanation: In the above example when method primeNumber() is called the mock object will return 5


MathMockVerfiyTest Some times it is important to verify whether certain method on the object is called or called how many times. In such case we can use static method verify
 
package test.com.lac.tut.mockito;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.*;

import org.junit.Before;
import org.junit.Test;

import com.lac.tut.mockito.Math;


public class MathMockVerfiyTest {
 Math mathObj;
 
 @Before
 public void create(){
  mathObj= mock(Math.class);
  when(mathObj.add(1,2)).thenReturn(3); 
 }
 
 @Test
 public void test() {
  //call the add function with 1,2 as arguments
  assertSame(mathObj.add(1,2),3);
  
  //Verify whether add method is tested with arguments 1,2 
  verify(mathObj).add(eq(1), eq(2));
  
  //Verify whether add method is called only once
  verify(mathObj,times(1)).add(1,2);
 }

}
Explanation: In the above example we try to assert that add method is called with arguments 1,2 and it is called only once. That can be achieved using verify method.


Download the source code of the above tutorial at http://www.luckyacademy.com/downloads.html



Monday, 23 June 2014

Find inside a file or directory

Problem: Find a word inside a file or directory

Solution: grep command can be used to find a word inside a file.


[root@iravath search]# grep -rnw '.' -e "Apple"
./names.txt:3:Apple
 
The above command search for word "Apple" inside a file. The word "Apple" was found in names.txt at line number 3.

Friday, 8 November 2013

Wednesday, 6 November 2013

Unicast liferay cluster on amazon EC2

Setting up liferay cluster on Aamzon EC2:

Amazon EC2 environment doesn’t allow multicasting that’s the reason. The steps mentioned at wiki http://www.liferay.com/web/ricardo.funke/blog/-/blogs/liferay-6-1-simple-cluster doesn’t work out of the box.

Environment:
·         Liferay 6.0.6 CE
·         Java version 1.7.0_45
·         Red Hat Enterprise Linux Server release 6.4
There are two entities that needs to be taken care while clustering
1.       Tomcat  HTTP Session replication
2.       Liferay cache replication
The scope of document is to cover “Liferay Cache Replication”. If you need information related to tomcat session replication please follow wiki http://techynfreesouls.blogspot.in/2012/04/liferay-cluster-on-amazon-ec2.html

Extract :
·         tcp.xml from “/liferay/tomcat/webapps/ROOT/WEB-INF/lib/jgroups.jar” and copy to /liferay/tomcat/webapps/ROOT/WEB-INF/classes
·         hibernate-clustered.xml from “/liferay/tomcat/webapps/ROOT/WEB-INF/lib/portal-impl.jar ” and copy to /liferay/tomcat/webapps/ROOT/WEB-INF/classes
·         liferay-multi-vm-clustered.xml from “/liferay/tomcat/webapps/ROOT/WEB-INF/lib/portal-impl.jar ” and copy to /liferay/tomcat/webapps/ROOT/WEB-INF/classes

Edit tcp.xml  and set <TCP  singleton_name="liferay_jgroups_tcp" bind_port="7800"

Edit Portal-ext.properties and set below attributes
web.server.display.node=true
#Setup hibernate
net.sf.ehcache.configurationResourceName=/hibernate-clustered.xml
#Setup distributed ehcache
ehcache.multi.vm.config.location=/liferay-multi-vm-clustered.xml
#In order to make use of jgroups
ehcache.bootstrap.cache.loader.factory=com.liferay.portal.cache.ehcache.JGroupsBootstrapCacheLoaderFactory
ehcache.cache.event.listener.factory=net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory
ehcache.cache.manager.peer.provider.factory=net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory
net.sf.ehcache.configurationResourceName.peerProviderProperties=file=/tcp.xml
ehcache.multi.vm.config.location.peerProviderProperties=file=/tcp.xml
ehcache.statistics.enabled=true
lucene.replicate.write=true

In my env I have two node cluster. The above changes needs to be performed on both the nodes.

Start tomcat on node1:
export JAVA_HOME=/jdk1.7.0_45
export PATH=$JAVA_HOME/bin:$PATH
export JAVA_OPTS="-Djgroups.bind_addr=node1 -Djgroups.tcpping.initial_hosts=node2[7800],node1[7800] -Djava.net.preferIPv4Stack=true -Xms256m -Xmx1024m -XX:MaxPermSize=512m -Dcom.sun.management.jmxremote   -Dcom.sun.management.jmxremote.port=12345   -Dcom.sun.management.jmxremote.ssl=false   -Dcom.sun.management.jmxremote.authenticate=false"
./startup.sh

Start tomcat on node2:

export JAVA_HOME=/jdk1.7.0_45
export PATH=$JAVA_HOME/bin:$PATH
export JAVA_OPTS="-Djgroups.bind_addr=node2 -Djgroups.tcpping.initial_hosts=node2[7800],node1[7800] -Djava.net.preferIPv4Stack=true -Xms256m -Xmx1024m -XX:MaxPermSize=512m -Dcom.sun.management.jmxremote   -Dcom.sun.management.jmxremote.port=12345   -Dcom.sun.management.jmxremote.ssl=false   -Dcom.sun.management.jmxremote.authenticate=false"
./startup.sh


If everything goes well. You should see following channels gets created .  Verify liferay log.


-------------------------------------------------------------------
GMS: address=node1-17685, cluster=EH_CACHE, physical address=10.0.123.5:33959
-------------------------------------------------------------------
-------------------------------------------------------------------
GMS: address=node1-36406, cluster=EH_CACHE, physical address=10.0.123.5:39875
-------------------------------------------------------------------
-------------------------------------------------------------------
GMS: address=node1-10244, cluster=LIFERAY-CONTROL-CHANNEL, physical address=10.0.123.5:59051
-------------------------------------------------------------------

-------------------------------------------------------------------
GMS: address=node1-22557, cluster=LIFERAY-TRANSPORT-CHANNEL-0, physical address=10.0.123.5:56066
-------------------------------------------------------------------
Test cases:
1.       Create a user in node1 and  search for the same user in node2. You should see user in node2
2.       Add a asset publisher portlet on page1  and access the same page on the other sever. The asset publisher portlet should be seen.

BTW..  ehcache.statistics.enabled=true and “-Dcom.sun.management.jmxremote   -Dcom.sun.management.jmxremote.port=12345   -Dcom.sun.management.jmxremote.ssl=false   -Dcom.sun.management.jmxremote.authenticate=false” are used for debugging purpose of the cache.




Wednesday, 30 October 2013

Deleting ipv6 address

Problem: Deleting ipv6 address in Linux
Solution:

ifconfig eth0 inet6 del fd00:7a06:a248:1:250:56ff:fe86:32cb/64

Tuesday, 29 October 2013

Counting number of files in a directory -Linux

Problem:  I want to find number of files in a directory
Solution:

 
[root@dragon bin]# ls -l | wc -l
25
[root@dragon bin]#