JMock2入门

说明:学习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
  public JUnitRuleMockery = new JUnitRuleMockery(); //必须为public

  @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);//调用被测试的方法
  }
}

 

转载于:https://www.cnblogs.com/linnicke/p/4975924.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值