Friday, January 13, 2017

Testing with JUnit in Liferay

Today we will see how to write JUnit test cases in Liferay. This can be helpful for unit testing. I assume that you have some idea about JUnit. If you want to learn JUnit you may watch Unit Testing with JUnit video tutorials.

So lets start this step by step:-

Step 1:-Create Project with Portlet
Create a Liferay project and then create a MVC portlet in it. Now inside your Controller just paste this method:-
Here we create a simple method getName that take user object and return user name prefix with Mr. We write test case for this method.

Step 2:-Create Another source folder
Create a source folder parallel to docroot. For this Right click on Project :-
New ->Others ->Search for Source Folder. Select Source folder and Click on Next and give Folder name as test/unit/src and click finish.

After this your project structure become:-

Step 3:-Run Ant Test
Right Click on build.xml->Liferay ->sdk->Test .This will create test-classes and test-results folder in your project which contain your test classes and test results.

Step 4:-Create JUnit Test
Create inside src (test/unit/src)and paste this:-

Your class give errors because of the jar file. So add mockito and powermock related jar in the lib folder of your project.These jars are available in sdk/lib. So copy the jars from lib folder of sdk and paste inside lib folder of your project.

Step 5:-Check Output

1)Successfull Test:-
Right Click on build.xml->Liferay ->sdk->Test

2)Failed Test:-
Now just change one line in HelloWorldTest as:-
 assertEquals("r Joe", helloWorld.getName(user));
Here i remove the M from Mr. 
Again Run test:-

As you can see on console This test is failed.

Note:- If you want to mock request and response object you may refer here

You can Download Source code from  Testing with Junit in Liferay.. 

No comments:

Post a Comment

Total Pageviews

Number Of Unique Visitor

Free counters!