说明:学习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);//调用被测试的方法
}
}