Wednesday, 24 June 2015

JUnit TestSuite: Running multiple test cases together.

Multiple Test cases can be run together in JUnit with Test Suite. Let’s say we have CalcTest.java and CalcTest1.java which need to be run together.

1.       Let’s create the class Calc.Java whose methods need to be tested. It has two methods add and subtract which will do the simple addition and subtraction of 2 numbers.

package com.main.java; 

public class Calc {
  
   public int add(int number1, int number2)
   {
          return number1+number2;
   }
  
   public int subtract(int number1, int number2)
   {
          return number1-number2;
   }

}


2.       Let’s Create CalcTest.java to test the add() method of Calc.java

package com.main.java; 

import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;

public class CalcTest {

       int checkValue;
       int value1;
       int value2;

       @Before
       public void setUp()
       {
       value1 = 5;
       value2 = 8;
       checkValue=13;
       }

       @Test
       public void testAdd() {
       assertTrue(checkValue==new Calc().add(value1, value2));
       }

}

3.       Let’s create another Test class CalcTest1.java to test the subtract() method of the Calc.java

package com.main.java;

import static org.junit.Assert.*;

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

public class CalcTest1 {

       int value1;
       int value2;

       @Before
       public void setUp()
       {
       value1 = 8;
       value2 = 5;      
       }

       @Test
       public void testSubtract() {
              assertTrue(3==new Calc().subtract(value1, value2));
       }

}

4.       Now create a JUnit Test Suite in eclipse, by clicking on File-> New -> Other -> JUnit Test Suite. Select the test classes to be included in the Test Suite as shown below in the screen shot.

Note:  Make sure to select the New JUnit 4 Suite on top otherwise the test classes won’t be displayed for selecting.


5.       As you can see, it has created the TestSuit with the name AllTests  with the 2 annotations. The annotations  @SuiteClasses and @RunWith are required for running the class as TestSuite.
In the @SuiteClasses annotation, both the test classes selected above are populated.

package com.main.java;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ CalcTest.class, CalcTest1.class })
public class AllTests {

}

6.       In the TestRunner.Java class file, give the TestSuite name i.e AllTests in the JUnitCore RunClasses() method. It will run both the test case classes mentioned above.

package com.main.java;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {

       public static void main(String args[])
       {
              Result result = JUnitCore.runClasses(AllTests.class);
             
                     for(Failure failure : result.getFailures())
                     {
                           System.out.println(failure.toString());
                     }
             
              System.out.println(result.wasSuccessful());
       }

}

Tuesday, 23 June 2015

Eclipse: Sample JUnit Test case Application

Sample JUnit Appliction in Eclipse

1.     Create a new project in Eclipse, let's say JUnitSample and setup the environment as mentioned in the previous post.
2.     Create a new Java class say Calc.Java under src.  This class has methods to perform the
      Arithmetic operations.
       Let’s create a method say add() which adds 2 numbers. It simply returns the sum of
       two integers.

package com.main.java;

public class Calc {

public int add(int number1, int number2)
{
return number1+number2;
}

}

3.      Now create a Junit Test case “CalcTest.Java” for the class “Calc”. select the class Calc and the method Add() while creating the JUnit test case in eclipse.

4.      Now you can see, there is a method added testAdd() with the annotation @Test.  The annotation signifies that the method will be run when we run the CalcTest test cases.

5.      Now let's add SetUp() method to predefine the values as shown in the example. Prefix it with @Before so that the method will be run before each test method runs.

6.      As you see in the below example, in the testAdd() method we are using assertTrue() method to check the value returned by add() method. It returns error, if the values doesn't match.

package com.main.java;

import static org.junit.Assert.*;

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

public class CalcTest {

int checkValue;
int value1;
int value2;

@Before
public void setUp()
{
value1 = 5;
value2 = 8;
checkValue=13;
}

@Test
public void testAdd() {
assertTrue(checkValue==new Calc().add(value1, value2));
}

}

7.    Now we will see how to run the test case. Let's create TestRunner.Java.


As you see in the below example, in the main method, we are using JUnitCore.runClassses() method to run the CalcTest test cases. It will run all the methods inside the CalcTest.Java which are annotated with @Test.

The result will be stored in Result and using the methods getFailures() and wasSuccessful() to get the failures and status respectively. If executed with the above values the example should print "true".

package com.main.java;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {

public static void main(String args[])
{
Result result = JUnitCore.runClasses(CalcTest.class);
for(Failure failure : result.getFailures())
{
System.out.println(failure.toString());
}

System.out.println(result.wasSuccessful());
}
}

Note:  You can run JUnit Testcases from the eclipse, simply by right clicking on the project -> Select Run AS -> select  JUnit Test. It will run all the test cases created.

Eclipse: Env Setup and Creating and Running a JUnit Test case.

Below are the steps to create and Run a JUnit Test case form the Eclipse

1.    Download the Junit jar from the location http://junit.org/ and also download the
     dependency jar hamcrest-core.jar.

2.    Create a new project in Eclipse. Right click on Project -> Properties -> Java Build Path -> Go to Libraries tab -> click on Add external Jars. Select the downloaded jars and add them.

3.     For creating a Junit test case, Right click on Project -> New -> Other -> Java -> Junit -> Select Junit Test Case.

a.     In the Next Window, Enter the name for the Junit Test Case and also select the Java class for which the test class is being created. Click on Next

b.     In the Next Window, Select the available methods for which the test method should be added and click on Finish.

4.    For running the test case, Right click on Project -> Run As -> JUnit Test. It should give the results accordingly.


If you are using Maven, Add the below dependency to pom.xml for JUnit. It will download the  JUnit and the hamcrest-core jars.

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>

Maven Plugin Error while creating the project in Eclipse


While creating the Maven project in Eclipse, If we get the below error it is due to the missing of the build life cycle mapping for m2e plugin.

- Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-compiler-plugin:2.5.1:testCompile
 (execution: default-testCompile, phase: test-compile)
- CoreException: Could not calculate build plan: Plugin org.apache.maven.plugins:maven-compiler-plugin:2.5.1 or one of its
 dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-compiler-plugin:jar:2.5.1:

Solution:

1.     Eclipse is providing the quick fix for ignoring the goal compile. Right click on the error and choose quick fix and select “Permanently mark goal compile in pom.xml as ignored”.  It will modify the pom.xml to ignore the maven-compiler-plugin for the goals.  Do it for compile and test Compile goals.
2.     Another way is to configure the same at the workspace level, go to Windows-> Preferences -> Maven -> Lifecycle Mappings. You can edit and reload the changed xml file.

Please see the more info on this common problem at the link:  https://www.eclipse.org/m2e/documentation/m2e-execution-not-covered.html

Please note I have used Eclipse Luna Version and Maven 3.3.3 versions. 

Sunday, 21 June 2015

Windows: "ftp" is not recognized as an internal or external command

In Windows OS, If you are getting the above error upon entering ftp in the command prompt follow the below steps.

1. Check whether "ftp.exe" is present in your C:/Windows/System32 path.

2. If present, set the PATH environment variable to point to this path.  Click on My Computer-> Properties -> Advanced System Settings -> Click on Environment Variables -> Select the PATH under System Variables and append the path to the "ftp.exe" at the end.

Friday, 19 June 2015

Junit Error: assertEquals() method undefined for the type

There are 2 ways to fix this error depending on the junit version you are using.

1. If you are using Junit 4.X,  you need to have the following import statement 
    import static org.unit.Assert.* 

   This Assert class contains the set of assertion methods useful for writing tests. 
   For ex it has assertArrayEquals(), assertEquals(), assertFalse(), assertTrue() etc. 

   All these static methods can be referenced with out prefix in the code.

   Please refer to the below link for more info on static class.


2. If you are using Junit 3.X , you need to import junit.framework.TestCase and your
    test class should extend the TestCase. By extending the junit.framework.TestCase,

    It inherits junit.framework.Assert default and your test class will have the access
    to the Assertion methods.

Thursday, 18 June 2015

Stpes to create Maven Project from Eclipse



Please make sure the environment variables M2_HOME, PATH etc are setup. If not, please refer to the other post on how to setup the environment.

1.     Once the environment is setup, eclipse configurations need to be updated for Maven. 

2.     Go to Window -> Preferences -> Maven-> Installations. Click on Add and select
       the Maven installation home directory.

3.     Go to "User settings" Under "Maven" and browse the user settings and global settings 
       point to  the settings.xml that should be present in your <<installation directory>>\conf folder.

4.     Go to File-> New -> select Maven Project.  Select the workspace and click on Next.

5.     It will list down all the archetypes available. Select the appropriate archetype. Let's say we want  to create a quick project select  “maven-archetype-quickstart” archetype from the list and click  on Next

6.     In the Next window enter the following details
a.         Group Id: <<com.sample.app>> //Similar to your package
b.        Artifact Id: <<SampleApp>> //your project name. 
c.         Version: <<0.0.1-SNAPSHOT>> //versioning used for project. 
d.        Package: <<Jar/War>> //when the packaging is done, it will create the Jar/War with   ArtifactId-Version. In our ex: SampleApp-0.0.1-SNAPSHOT.Jar


The above steps should create a project with name SampleApp.




Wednesday, 17 June 2015

Steps to add Custom Attributes in liferay portal


Below are the steps to be followed for adding the custom attributes to the existing resources provided by liferay portal.

1. Login to Liferay Portal with Admin and go to Control Panel

2. Select "Custom Fields"  Under "Configuration" section.

3. It will list down the list of existing resources. select the edit button against the resource
    to which you want to add the custom attribute.

4. Upon select Edit, It will show the resource with the button "Add Custom Field". Click on It.

5. you will be asked to enter Key and Type. Please give the name and datatype of the
    custom attribute to store in. The key is the name with which the custom attribute
    can be accessed further. Click on Save.

6. Upon Save, It will list down the custom attributes added to a particular selected resource.
    It will also display the Key for the attribute.







Steps to create Maven Project from Command line

Below are the steps to be followed for creating a simple Maven project from command line.

1.  Please make sure the enviroment is setup. please see the previous post on how to set up
     the Maven environment.

2. Open command prompt and go to the folder where you want the project to be created
     and type the below command.
       mvn archetype:generate -DgroupId=com.myapp  //Project packaging
      -DartifactId=mavendemo  //Project name
      -DarchetypeArtifactId=maven-archetype-quickstart  //Template
      -DinteractiveMode=false 

  • The above command creates a project mavendemo with the entire project structure based on the "maven-archetype-quickstart" template.
  • It will also download all the required dependencies from the Maven central repository and store it in local repository.
  • All the source code will be put under src/main/java folder and all the test code will be put under src/test/java
  • It will also create pom.xml. It is the Project Object Model which is the fundamental unit of work in Maven. It contains all the project information like plugins, dependencies, directory sturcture, configuration details to build the project.

If you want the project to be imported into eclipse, follow the below steps.

3. go to the project folder where it is created (in our ex: mavendemo folder) and type command
    mvn eclipse:eclipse. This will generate the eclipse related env files like .classpath
    and .project.

4. In eclipse go to File-> Import -> General -> Existing Projects into Workspace.




Tuesday, 16 June 2015

Maven Environment Setup

Below are the steps to be followed for setting up Maven Environment

Step1: Verify Java Installation on your machine.
           Open the command prompt and type java -version. It should return us the Java version
           we are using.

If the JDK is not installed on your machine, get it from Oracle downloads page.

Step2: Set JAVA_HOME env variable to point to the installation directory of Java.
          In windows, open the computer -> properties-> Advanced System Settings ->
          Click on Env variables.
          JAVA_HOME = C:\Program Files\Java\jdk1.8.0_40

Step3: Append the path to the JDK bin directory to the PATH env variable.
          Open the env variables tab, and append C:\Program Files\Java\jdk1.8.0_40\bin to PATH.

Step4: Extract the Maven Archive to the local directory.

Step5: Set the Env variable M2_HOME to the Maven directory
            M2_HOME = D:\apache-maven-3.3.3

Step6: Append Maven bin directory (D:\apache-maven-3.3.3\bin) to the PATH env variable.

Step7: Verify Maven Installation. Open the command prompt and type in mvn --version.
           It should give us the version details.

With this, the maven environment setup is done.
         




How to draw UML Sequence Diagrams in Visio 2013

Below are the steps to draw UML sequence diagram in Viso.

Open the Visio and
-> select the Blank Drawing
-> select the US Units
-> Click on Create
-> Click on More Shapes option in the left pane. It will open the tab to browse the shape categories
-> Go to Software and Database ->Software -> Click on UML Sequence.
     It will open up the stencils for the UML sequence diagram.

Let's say for example if we want to draw the sequence digaram for the interactions between two systems.  Ex: System 1 and System 2.

-> Drag Object Lifeline stencil to the drawing page. Double click on the box and name it System1.
-> Similarly drag another object lifeline stencil to the page and name it System2.
-> Drag the Activation stencis to the System 1 (the vertical line). Drag another to System 2 lifeline.
-> For representing any contact from System 1 to System2 like messages, API calls etc ,drag -> (Arrow) message stencil between two systems. The origin of the arrow should be on System1, Activation line and the Arrow should point to the System 2 Activation lifeline.
-> For the return message, use  <-- (return Arrow with dotted lines) stencil.
-> for any functionality within the system, use Self Message stencil.



Friday, 12 June 2015

How to add or get custom field data in liferay portal using API

Liferay is providing the following remote service com.liferay.portlet.expando.service.impl.ExpandoValueServiceImpl which can be used for adding/selecting/updating the custom field data.

Here are the parameters to be passed in:

1.    CompanyId: company id that is assigned
2.    Class Name: The entity name that we have created the custom attribute for
3.    TableName: Is always CUSTOM_FIELDS
4.    ColumnName: The name given for the attribute
5.    classPK: Primary key value within the entity.
6.    Data: the value to be updated.

For adding or updating a single field, The API is ‘/expandovalue/add-value'.
For adding or updating multiple fields the API is ‘/expandovalue/add-values'.
For getting the data (single or multiple) the API is '/expandovalue/get-data' 

Below are the sample examples - Language is the custom field added.

For Add

Liferay.Service(
  '/expandovalue/add-value',
  {
    companyId: 101233,
    className: 'com.liferay.portal.model.User',
    tableName: 'CUSTOM_FIELDS',
    columnName: 'Language',
    classPK: 10234,
    data: 'English'
  },
  function(obj) {
    console.log(obj);
  }
);

For adding multiple Values (Here Language and Notification Preferences are custom Fields)
Provide the input to attributeValues as Collection object.

Liferay.Service(
  '/expandovalue/add-values',
  {
    companyId: 101233,
    className: 'com.liferay.portal.model.User',
    tableName: 'CUSTOM_FIELDS',
    classPK: 10234,
    attributeValues: {Language:English, Notification Preference:Email}
  },
  function(obj) {
    console.log(obj);
  }
);

For getting the data (In column Names give the multiple values for getting more than one column data)

Liferay.Service(
  '/expandovalue/get-data',
  {
    companyId: 101233,
    className: 'com.liferay.portal.model.User',
    tableName: 'CUSTOM_FIELDS',
    columnNames: Language, Notification Preference,
    classPK: 10234
  },
  function(obj) {
    console.log(obj);
  }
);


Tuesday, 9 June 2015

java.lang.NoClassDefFoundError: org/json/JSONObject

I was getting the above error even after adding the required jar (java-json.jar) to the library.

I have followed the below steps to add this jar to the library.

Click on Project -> Properties -> Java Build Path (on left panel) -> select Libraries Tab -> click on Add External JARs  and import the jar.

So in order to avoid the above problem I add the above jar to Deployment Assembly as well.

Click on Project -> Properties -> Deployment Assembly (on left panel) - > click on Add -> Select Java Build Path Entries -> select the Jar.

Not sure whether it is the good approach or not but it solved my problem.

Another way to avoid these dependency errors is to use Maven.

Saturday, 6 June 2015

How to do Exponential Calculation in MS Excel

MS Excel offers ways to do math calculations very easy. By leveraging POWER() function we can simply calculate the exponential.

Lets say if we want to calculate A^B . In this the Base value is A and the exponential value is B.

So in the Excel ->  We can give =POWER(A, B) to calculate A^B.

Example -> 4^8 can be calculated in excel with =POWER(4,8)

Java SE 7: Catching Multiple Exceptions

In Java SE 7 and later, a single catch block can handle more than one type of exception. This will avoid the code duplication.

For ex: Before Java SE 7, we would write the following code to catch multiple exceptions.

catch(IOException ex){
logger.log(ex);
throw ex;
} catch(SQLException ex){
logger.log(ex);
throw ex;
}

The same can be written as below in Java SE 7 and later which will avoid the duplicate code.

catch(IOException|SQLException ex){
logger.log(ex);
throw ex;
}

multiple exceptions are separated by vertical bar (|).

Note: If catch block handles more than one exception, then the catch parameter is implicitly final. So we can not assign any new value to the parameter (ex in the example).