码迷,mamicode.com
首页 > 其他好文 > 详细

JMock2入门

时间:2015-11-18 22:41:18      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

说明:学习JMock官网的Getting Started的笔记

例子:为测试publish/subscribe发布/订阅信息系统的publisher(发布者),mock subscriber(订阅者)对象

接口subscriber如下:

  interface Subsciber {

    void receive(String message);

  }

1. 引用Jar包

  必须包:  jmock-2.6.1.jar, hamcrest-core-1.3.jar, hamcrest-library-1.3.jar

  注意: 添加的时候,注意把JUnit4的order放到最后。因为junit4它自己带了一个Hamcrest jar。 
      要是不注意顺序的话,有可能报 java.lang.SecurityException: class "org.hamcrest.TypeSafeMatcher"‘s signer information does not match signer information of other classes in the same package。 

2. 编写测试类

  注:使用的是测试框架是JUnit4

方式1:

public class TestPublisher {
  private Mockery context = new Mockery(); 

  @Test
  public void testOneSubscriberReceivesAMessage(){
    Publisher publisher = new Publisher();

    final Subscriber subscriber = context.mock(Subscriber.class);
    publisher.add(subscriber);

    final String message = "message";

    //定义预期行为
    context.checking(new Expectations(){
      {
        oneOf(subscriber).receive(message);
      }
    });

    publisher.publish(message);//调用被测试的方法
    context.assertIsSatisfied(); //验证定义的预期行为是否执行了。 如果该测试方法是异常测试,则该方法会失效
  }
}

方式2:

使用注解@RunWith(JMock.class)和JUnit4Mockery代替了需要在每个测试方法中调用context.assertIsSatisfied(),并转换了错误,如下:

技术分享

 

 

技术分享

 

@RunWith(JMock.class)

public class TestPublisher {
  private Mockery context = new Junit4Mockery(); 

  @Test
  public void testOneSubscriberReceivesAMessage(){
    Publisher publisher = new Publisher();

    final Subscriber subscriber = context.mock(Subscriber.class);
    publisher.add(subscriber);

    final String message = "message";

    //定义预期行为
    context.checking(new Expectations(){
      {
        oneOf(subscriber).receive(message);
      }
    });

    publisher.publish(message);//调用被测试的方法
    context.assertIsSatisfied(); 
  }
}

方式3:

使用JUnitRuleMockery和注解@Rule代替了@RunWith(JMock.class)和JUnit4Mockery

public class TestPublisher {

  @Rule
  private JUnitRuleMockery = new JUnitRuleMockery(); 

  @Test
  public void testOneSubscriberReceivesAMessage(){
    Publisher publisher = new Publisher();

    final Subscriber subscriber = context.mock(Subscriber.class);
    publisher.add(subscriber);

    final String message = "message";

    //定义预期行为
    context.checking(new Expectations(){
      {
        oneOf(subscriber).receive(message);
      }
    });

    publisher.publish(message);//调用被测试的方法
  }
}

 

JMock2入门

标签:

原文地址:http://www.cnblogs.com/linnicke/p/4975924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!