jmock第一次接触


尝试jmock,一直听说jmock怎么怎么好,感觉一个框架灵活度高了必然功能不是很全,要找个轻巧又好用的还真难。

简单接口:

public interface Foo {

public String hello(String name);
}

简单实现:

public class FooImpl implements Foo {

public String hello(String name) {
return "hello " + name;
}
}

测试类(junit4.4----一定要4.4,eclipse内置的4.3不行。。):

import static org.junit.Assert.assertEquals;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMock.class)
public class FooTest {
private Mockery context;

@Before
public void setUp() throws Exception {
context = new JUnit4Mockery();
//context.setImposteriser(ClassImposteriser.INSTANCE);
}

@After
public void tearDown() throws Exception {
}

@Test
public void testHello() {
final Foo foo = context.mock(Foo.class);
context.checking(new Expectations() {
{
// one表示foo对象的hello方法调用一次,will返回"foo",好理解吧
one(foo).hello("czy");
will(returnValue("hello czy"));
// 可以再来一句,表示连续调用返回不同的结果
// one(foo).hello(); will(returnValue("xxx"));
one(foo).hello("good");
will(returnValue("111"));
}
// 可以定义多个block

// {
// one(foo).hello("good");
// will(returnValue("111"));
// }
});
assertEquals("hello czy", foo.hello("czy"));
assertEquals("111", foo.hello("good"));
// 如果有没有使用的mock,测试不通过
context.assertIsSatisfied();

}

}

testng版本:

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FooTest {
private Mockery context;

@BeforeTest
public void setUp() throws Exception {
context = new Mockery();
//context.setImposteriser(ClassImposteriser.INSTANCE);
}


@AfterTest
public void tearDown() throws Exception {
}


@Test
public void testHello() {
final Foo foo = context.mock(Foo.class);
context.checking(new Expectations() {
{
// one表示foo对象的hello方法调用一次,will返回"foo",好理解吧
one(foo).hello("czy");
will(returnValue("hello czy"));
// 可以再来一句,表示连续调用返回不同的结果
// one(foo).hello(); will(returnValue("xxx"));
one(foo).hello("good");
will(returnValue("111"));
}
// 可以定义多个block

// {
// one(foo).hello("good");
// will(returnValue("111"));
// }
});
Assert.assertEquals(foo.hello("czy"), "hello czy");
Assert.assertEquals(foo.hello("good"),"111");
// 如果有没有使用的mock,测试不通过
context.assertIsSatisfied();

}

}

顺带着testng也会用了,junit熟悉了之后感觉testng也很简单,几个annotation也几乎一样,testng需要导入的库比junit也少,方便啊。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值