Friday, September 10, 2010

Unit Testing for J2ME - JMUnit

In professional development environment it is a common practice to create Unit Tests. On Java platform there are lots of research and development done on Unit Tests for Enterprise Edition. As far as Java Micro Edition is concerned one of the framework available is JMUnit.

Creating and executing a test case using jmunit is quite simple and can be done without wasting much time to explore it. Following steps will guide you how to work with jmunit:

  •  In your mobile application right click on package (where you want to create a unit test) and select option 'New > Empty JMUnit Test'.
  • It will create a unit test class for you that will look like this:
    /*
     * ABCTest.java
     * JMUnit based test
     *
     */
    
    package hello;
    
    
    import jmunit.framework.cldc10.*;
    
    /**
     * @author rizwan
     */
    public class ABCTest extends TestCase {
        
        public ABCTest() {
            //The first parameter of inherited constructor is the number of test cases
            super(0,"ABCTest");
        }            
    
        public void test(int testNumber) throws Throwable {
        }    
    }  

    • Next you will create a test method in same class and call it in test() using switch cases.
    • Total count of test cases will also be mentioned in unit class constructor.
    • Now the code will look like this:

    /*
     * ABCTest.java
     * JMUnit based test
     *
     */
    
    package hello;
    
    
    import jmunit.framework.cldc10.*;
    
    /**
     * @author rizwan
     */
    public class ABCTest extends TestCase {
        
        public ABCTest() {
            //The first parameter of inherited constructor is the number of test cases
            super(1,"ABCTest");
        }            
    
        public void test(int testNumber) throws Throwable {
            switch(testNumber){
                case 0: 
                    testOne();
                    break;
            }
        }    
    
        private void testOne() throws Exception{
            String tmp = "Hello Rizwan";
            assertEquals(tmp, "Hello Rizwan");
        }
    } 

    • After that you have to mention 'ABCTest' as your Midlet.
    • Go into 'project properties > Application Descriptor > MIDlets' and define unit test name and package here.
    • Run application and you will also get Test option on screen:  
    • Test the project and it will show you the results




    Your mobile test case is ready !

    rizzz86

    No comments: