我有一个像这样的junit方法:
public void testMyStuff() {
IMockBuilder<BackingBean> builder = createMockBuilder(BackingBean.class);
builder.addMockedMethod("getMyFacesContextSessionMap");
BackingBean bean = builder.createMock();
MyVO MyVO = new MyVO();
List<MyVO> MyVOList = new ArrayList<MyVO>();
HttpServletRequest req = createMock(HttpServletRequest.class);
bean.setHttpServletRequest(req);
MyVOList.add(buildMyVO());
expect(bean.getMyFacesContextSessionMap()).andReturn(
new HashMap<String, Object>());
expect(ac.getBean("MyService")).andReturn(service);
expect(MyFacade.getMyStuff(MyVO)).andReturn(MyVOList);
expect(bean.getMyFacesContextSessionMap()).andReturn(
new HashMap<String, Object>());
replay(bean, MyFacade);
bean.setService(service);
String returnString = bean.myStuff();
assertEquals("myNo", returnString);
}
当我在eclipse中将其作为junit运行时,我收到此错误:
java.lang.AssertionError:
Unexpected method call MyFacadeLocal.getMyStuff(MyVO@8c64cdd8):
MyFacadeLocal.getMyStuff(MyVO@d79a467f): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:85)
at $Proxy1.getMyStuff(Unknown Source)
我不明白如何纠正这个问题。有人可以帮助我吗?
答案 0 :(得分:0)
这意味着方法
getMyStuff
带有as参数的永远不会在你的支持bean中调用MyVO。检查是否真的调用了该方法。如果是这种情况,请为MyVO实现equals()和hashCode()方法,因为它可能不被识别为相同的元素,因为它是一个不同的对象。
错误消息只是告诉您期望使用您指定的EXACT参数的方法,但是没有遇到...
答案 1 :(得分:0)
ArgumentMatcher的示例:
public class CollectionCountMatcher implements IArgumentMatcher
{
private int expectedCount;
public CollectionCountMatcher(int count) {
super();
this.expectedCount = count;
}
public boolean matches(Object actual) {
return (actual instanceof Collection)
&& ((Collection) actual).size() == expectedCount;
}
public static final Integer eqObject(Integer inValue) {
EasyMock.reportMatcher(new CollectionCountMatcher (inValue));
return inValue;
}
public void appendTo(StringBuffer buffer) {
buffer.append("collectionContains(" + expectedCount + ")");
}
}
您创建了一个MyVOMatcher,并按照以下方式调用您的模拟方法:
expect(MyFacade.getMyStuff(MyVOMatcher.eqObject(MyVO))).andReturn(MyVOList);
编辑:或者你也可以做什么,但这种工作方式不那么严格,不检查不同的对象是这样做的:
expect(MyFacade.getMyStuff(EasyMock.anyObject(myVO.class))).andReturn(MyVOList);
这肯定会起作用,但是当然你可以传递所有可能的参数,只要它是MyVO类型
答案 2 :(得分:0)
我想这是因为getMyStuff是一个静态方法。使用EasyMock模拟静态方法并不理想。也许考虑Powermock,如果你想在EasyMock中做到这一点,你可以尝试以下方法:
您可以将静态调用移动到方法,在测试类中测试类的实例化中覆盖此方法,在测试类中创建本地接口并在覆盖方法中使用其方法:
private interface IMocker
{
List<MyVO> getMyStuff(MyVO myVO);
}
IMocker imocker = EasyMock.createMock(MyFacade.class);
...
@Override
List<MyVO> getMyStuff(MyVO myVO)
{
imocker.getMyStuff(myVO);
}
...
EasyMock.expect(imocker.getMyStuff(EasyMock.anyObject(myVO.class))).andReturn(true);