在运行第一个 JMock 程序时,抛出了如下错误信息:
Exception in thread "main" unexpected invocation: userService.getUserInfo(<100>)
expectations:
expected once, never invoked: userService.getUserInfo(<1000>); returns <User{id=1000, name='admin'}>
parameter 0 did not match: <1000>, because was <100>
what happened before this: nothing!
at org.jmock.api.ExpectationError.unexpected(ExpectationError.java:23)
at org.jmock.internal.InvocationDispatcher.dispatch(InvocationDispatcher.java:85)
at org.jmock.Mockery.dispatch(Mockery.java:231)
at org.jmock.Mockery.access$100(Mockery.java:29)
at org.jmock.Mockery$MockObject.invoke(Mockery.java:271)
at org.jmock.internal.InvocationDiverter.invoke(InvocationDiverter.java:27)
at org.jmock.internal.FakeObjectMethods.invoke(FakeObjectMethods.java:38)
at org.jmock.internal.SingleThreadedPolicy$1.invoke(SingleThreadedPolicy.java:21)
at org.jmock.lib.JavaReflectionImposteriser$1.invoke(JavaReflectionImposteriser.java:33)
at com.sun.proxy.$Proxy0.getUserInfo(Unknown Source)
at com.huangx.jmock.OrderService.findOrder(OrderService.java:19)
at com.huangx.jmock.Client.main(Client.java:35)
部分代码如下:
package com.huangx.jmock; import org.jmock.Expectations; import org.jmock.Mockery; public class Client { public static void main(String[] args) { final User user = new User(100, "admin"); // 建立一个 test 上下文对象。 Mockery context = new Mockery(); // 生成一个mock对象 final UserService userService = context.mock(UserService.class); // 设置期望 context.checking(new Expectations() { { oneOf(userService).getUserInfo(1000); will(returnValue(user)); } }); OrderService orderService = new OrderService(); // 设置mock对象 orderService.setUserService(userService); // 调用方法 orderService.findOrder("ID-1000"); } }
上面错误信息是因为我们返回的值 final User user = new User(100, "admin"); 和 oneOf(userService).getUserInfo(1000); 语句 getUserInfo 语句指定的参数 1000 不一致。
要解决上面的问题,我们有两种方式:
(1)方式一:修改返回值
final User user = new User(100, "admin");
改为
final User user = new User(1000, "admin");
(2)方式二:修改调用参数
// 设置期望 context.checking(new Expectations() { { oneOf(userService).getUserInfo(1000); will(returnValue(user)); } });
改为
// 设置期望 context.checking(new Expectations() { { oneOf(userService).getUserInfo(100); will(returnValue(user)); } });