JMock资料本来就少, JMock2.0更是少之又少,官方那可怜巴巴的几个连接,似乎并不能说明一个简单的例子应该怎么运行。
我结合官方那个例子,简单的写了一个最简单的JMock实例。
废话少说,先把jar包加上,我试了一下,下面似乎是必须的:
jmock.jar, jmock-junit.jar, junit.jar, hamcrest-core.jar, hamcrest-library.jar
配置好了,可以开始玩Mock了。与Spring相似的,Mock也有两种代理机制,一种是面向接口的,一种是面向普通Java类的(需要cglib.jar支持)。我这里使用的是面向接口的。先写一个简单的接口吧:
java 代码
<wbr>public</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr><wbr>
<wbr>interface</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> IUserService {
<wbr>public</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> String sayHello(String str); }
实现也非常简单:
java 代码
<wbr>public</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr>
<wbr>class</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> UserServiceImpl
<wbr>implements</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> IUserService {
<wbr>public</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> String sayHello(String str) {
<wbr>return</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> str; } }
开始测试吧:
java 代码
<wbr>import</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> junit.framework.TestCase;
<wbr>import</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> org.jmock.Expectations;
<wbr>import</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> org.jmock.Mockery;
<wbr>public</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr>
<wbr>class</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> UserServiceTest
<wbr>extends</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> TestCase { Mockery context =
<wbr>new</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> Mockery(); IUserService userService =
<wbr>null</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr>;
<wbr>protected</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr>
<wbr>void</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> setUp() { userService = context.mock(IUserService.
<wbr>class</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr>); }
<wbr>public</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr>
<wbr>void</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> testSayHello() {
<wbr>final</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> String message = "HelloSuperLeo"</wbr><wbr style="LINE-HEIGHT: 1.3em">; context.checking(
<wbr>new</wbr><wbr style="LINE-HEIGHT: 1.3em"></wbr></wbr><wbr> Expectations() { { one(userService).sayHello("HelloSuperLeo"</wbr><wbr style="LINE-HEIGHT: 1.3em">); will(returnValue(message)); } }); // 测试成功 </wbr><wbr style="LINE-HEIGHT: 1.3em"> String result = userService.sayHello("HelloSuperLeo"</wbr><wbr style="LINE-HEIGHT: 1.3em">); // 测试失败 </wbr><wbr style="LINE-HEIGHT: 1.3em"> // String result = userService.sayHello("fdjsasdfa"); </wbr><wbr style="LINE-HEIGHT: 1.3em"> assertSame(result, message); } }
在JMock2.0后, Mock已经改成Mockery了, 所以大家要注意这个区别。
上面的代码讲的就是一件事: 模拟当传入参数(这里是:"HelloSuperLeo")时,返回预先的值(这里是:message="HelloSuperLeo")。然后运行要测试的方法(这里是:userService.sayHello(String str))。
Mock要解决的问题在这个简单的例子里似乎并不能体现出来,不过,先让大家知道怎么用才是最重要的吧