Friday, June 8, 2012

Implementing Junit in to a GWT application

Download JUnit
Download latest junit.jar and copy it to the war/WEB-INF/lib directory.

Add Libraries to the Classpath
  • Right click on to the application in Eclipse
  • Choose Properties
  • Choose Java Build Path
  • Choose Libraries
  • Click on to Add Jar 
  • Select the junit.jar file
  • Click Ok to add them to the build path

Create a folder for tests
It is best practice to put tests in to a seperate directory outside the source folder but still inside the project folder. I created a different source folder called "tests" inside my project folder and added the same java package. If your java package inside the src folder is "com.yourcompany.yourapp", you can create the same java package in the tests folder. I use following java package path: "com.yourcompany.yourapp.junit" to put all my junit tests.

  • Right click on to your application folder within Eclipse
  • Choose New -> Source Folder
  • Name the folder tests
  • Then right click on to the tests source folder
  • Choose New -> Package
  • Name the package com.yourcompany.yourapp.junit
  • Click OK

That's it. You are ready to write tests.

Create a sample test case
Next we will write a simple test to see if everything is working.

  • Right click on to the com.yourcompany.yourapp.junit package
  • Choose New -> Class
  • Name the class MyFirstTest.java
  • Click OK

Add the following code to the MyFirstTest.java class:

MyFirstTest.java
package com.yourcompany.yourapp.junit;

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

public class MyFirstTest {
    @Test
    public void testAddition() {
        assertEquals(4, 2 + 2);
    }
}



Run the JUnit Test

  • Right click on to your application folder within Eclipse
  • Choose Run as -> JUnit Test

Eclipse should open a new window and display the results of the JUnit test.


No comments:

Post a Comment