Five ‘s Weblog

October 16, 2007

An example of JMock!

Filed under: Programming — by powerdream5 @ 8:35 pm
Tags: , , ,

        Test-Driven Development(TDD) has already been proved to be a best practice for software ddevelopment. And In the process of TDD, we frequently come across such situation that one method has to communicate with other classes to realize its function. Therefore, in order to test this method, we have to create the class it is going to communicate with firstly. However, this will deviate from the concept of unit testing. Fortunately, we have some useful tools to handle this kind of situation, such as JMock and EasyMock, which can mock the objects the method interact with, so that we don’t need to crate a real object to finish the testing for that method.

10_16_3_2007.jpg

        Today, I am going to show an example of the use of JMock. Firstly, you need to download JMock and JUnit. Do not use the latesting version (junit 4.4) of JUnit. In this example, I use JUnit 4.3.1 and JMock 2.2. Then add the following packages into your classpath: junit-4.3.1.jar, jmock-2.2.-.jar, jmock-junit4-2.2.0.jar, hamcrest-core-1.1.jar and hamcrest-library-1.1.jar.
        I am going to create a small application which can say different greetings to the client according to different time. For example, it outputs “Good morning, ***” in the morning, and outputs “Good evening, ***” in the evening. According to the procedure of TDD, we firstly create a test case.

//import some necessary classes from the package of JUnit4
import org.junit.Test;
import static org.junit.Assert.asserEquals;

public class TestJMockCase{

   @Test
   public void testSayGreeting(){
         Greeting o = new Greeting();
         String out = o.SayGreeting(“wu cao”);
         assertEquals(“Good afternoon, wu cao”, out);
   } 
}

        Because we haven’t created the class of Greeting, we will fail in compiling this test case. In order to make it through compilation, we need to code the Greeting class. And we find the Greeting class have to communicate with the other class named GreetingTime to get the the words of greeting.

public class Greeting{
        //we have to define GreetingTime as an interface
        //I am goint to explain it in the later
        private GreetingTime gt;
        public void setGreetingTime(){
               this.gt = gt;
        }

        public String sayHello(){
               String greeting = gt.getGreeting();
               return greeting+”, “+name;  
        }

        In order to compile successfully, we also need to create the class of GreetingTime. But now, our focus is not on the GreetingTime class, so we decide to use mock object.

public interface GreetingTime{
        public String getGreeting();
}

       Because we are going to mock the GreetingTime class, we have to define it as an interface, which is a prerequisite for the mock object. Therefore, we have to use the setter method to inject the instance of GreetingTime to Greeting, (we cannot use the new keyword on an interface).

       Then, we have to make some changes to the test class we created before, because we are going to mock the GreetingTime.

//import some necessary classes from the package of JUnit4
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
//import some necessary classes from the package of JMock2.2
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.Expectations;
@RunWith(JMock.class)
public class TestJMockCaseUsingJMock{
        //create the context for the mock object
        Mockery context = new JUnit4Mockery();

        @Test
         public void testSayHello()
        {
             //Mock the GreetingTime class using the technology of reflection
             //you have to define it as a final variable
             //since it is going to be used in a inner class
             final GreetingTime gt = context.mock(GreetingTime.class);
             Greeting g = new Greeting();
              g.setGreetingTime(gt);

             //set the expection for the mock object
             context.checking(new Expectations(){{
                   //the mock object will call the getGreeting method once
                  //and we assume that is returns “Good afternoon”
                  one(gt).getGreeting(); will(returnValue(“Good afternoon”));
              }});

             String out = g.sayHello(“wu cao”);
             //compare the result and expected value
             assertEquals(“Good afternoon, wu cao”,out);
         }
}

Now, you can open the command widnow to test.

10_16_2_2007.jpg

10_16_1_2007.jpg

22 Comments »

  1. FYI, the latest version of JMock (2.3, I believe) does work with the latest version of JUnit (4.4). Share and enjoy,

    David Saff

    Comment by David Saff — October 19, 2007 @ 9:51 am |Reply

  2. Good example.. thanks

    Comment by Anurag — April 28, 2008 @ 8:51 am |Reply

  3. Typo:

    public void setGreetingTime(){
    this.gt = gt;
    }

    should be: public void setGreetingTime(GreetingTime gt)

    Comment by Cubeek — May 29, 2008 @ 10:59 am |Reply

  4. This test program doesn’t work with jmock 2.5.
    The following error occurred:
    class file for org.junit.internal.runners.JUnit4ClassRunner not found
    @RunWith(JMock.class)

    Typo:
    Should change
    String out = o.SayGreeting(”wu cao”);
    to
    String out = o.sayHello(“wu cao”);

    Comment by otoro — July 22, 2008 @ 9:59 am |Reply

  5. Abla iyiymis

    Comment by Aman be yaw — August 23, 2008 @ 2:36 am |Reply

  6. Thank you so much for the example. Very good comments I might add.

    Comment by tony leung — December 12, 2008 @ 6:31 pm |Reply

  7. Very good example…Thanks for sharing!

    Comment by Leena — February 20, 2009 @ 10:33 am |Reply

  8. Thanks. This is really helpful.

    Comment by Praveen — October 1, 2009 @ 4:21 pm |Reply

  9. Hi,
    Can anyone give me the process how to write jmockit test cases for the Controllers in Portal Development.

    Comment by vik — February 18, 2010 @ 7:51 pm |Reply

  10. Heh am I actually the only comment to your awesome article?!?

    Comment by Marlene Gleason — May 26, 2010 @ 10:47 pm |Reply

  11. Your the best!!!!

    i have working for these codes in 3 days, you just made my life easer!! again regards!!!!

    Comment by Prinsipe Luha — June 3, 2010 @ 2:28 am |Reply

  12. Very easy and nice example. Easy to understand and implement.
    Thanks a lot for sharing this good tutorial.

    Thansk,

    Binod Suman

    Comment by Binod Suman — September 29, 2010 @ 1:34 am |Reply

  13. You saved my job. I am in company where I am working with JUnit and JMock and EasyMock. I dont know anything about it. Now its make sense and I think I can do it. Thank you very much.

    Comment by Abdul Hafiz — January 13, 2011 @ 5:27 pm |Reply

  14. good example. can you able to provide simple example as above under other mock frameworks like mockito ..etc. Also which mock framework is good overall?

    Comment by Srihari Konakanchi — February 18, 2011 @ 8:19 am |Reply

  15. Nice article, helped me setup the whole thing and ran a jMock test successfully. THANKS AGAIN !

    Comment by Kumar Manish — May 26, 2011 @ 4:00 am |Reply

  16. nice example

    Comment by nice and simple example — October 27, 2011 @ 1:07 pm |Reply

  17. very good example

    Comment by satish — October 27, 2011 @ 1:08 pm |Reply

  18. Really awesome article!

    Comment by Jaykishan — November 23, 2011 @ 4:53 am |Reply

  19. It is simplest and most useful example for basic understanding of JMock

    Comment by Pbs — May 14, 2012 @ 6:01 am |Reply

    • Thanks for all you efforts, really appreciated !!

      Comment by Pbs — May 14, 2012 @ 6:02 am |Reply

  20. Hello there, just turned into aware of your blog through Google, and found that it is really informative. I’m going to be careful for brussels. I will appreciate in case you proceed this in future. Lots of other folks can be benefited out of your writing. Cheers!

    Comment by film,dizi,program,oyun,webmaster,wordpress,hdtv,dvbrip,xvid,windows 8,windows 7 — December 9, 2012 @ 11:51 pm |Reply

  21. I have noticed you don’t monetize your website, don’t waste your traffic,
    you can earn extra cash every month because you’ve got hi quality content.
    If you want to know how to make extra $$$, search for: best adsense alternative Wrastain’s tools

    Comment by 86Prince — August 24, 2017 @ 11:58 am |Reply


RSS feed for comments on this post. TrackBack URI

Leave a reply to Kumar Manish Cancel reply

Blog at WordPress.com.