EasyMock:静态方法和前面方法调用的缺失行为定义'?

时间:2015-05-29 13:49:06

标签: easymock

我有以下核心类MessagesUtil,它根据语言环境从特定的bundle返回一个消息字符串 - 所有getMessage()方法都是静态的

public class MessagesUtil { ..

    public static String getMessage(HttpServletRequest request, String key, String bundle) {
        MessageResources resources = (MessageResources)request.getAttribute(bundle);
        String message = resources.getMessage((Locale)request.getSession().getAttribute("org.apache.struts.action.LOCALE"), key);
        return message;
    }
}

我正在尝试编写一个单元测试,它覆盖了一个调用MessageUtils对象的业务类。下面的相同测试代码显示了我如何模拟请求和会话,返回MessageResources然后返回特定的消息键

import com.infonova.easymock.annotation.Mock;
import org.apache.struts.util.MessageResources;
import org.junit.Assert;
import org.junit.Test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Locale;

import static org.easymock.EasyMock.expect;

public class MappingsUtilsEasyMockTest {

    @Mock
    private HttpServletRequest request;

    @Mock
    private HttpSession session;

    @Mock
    private MessageResources messageResources;

    @Test
    public void mockMessagesUtilTests() {

        String key = "ordermanagement.error.general";

        expect(request.getAttribute("CustomerManagementResources")).andReturn(messageResources);
        // the locale
        Locale locale = Locale.ENGLISH;
        expect(session.getAttribute("org.apache.struts.action.LOCALE")).andReturn(locale);
        // the locale specific String from the message Resource
        expect(messageResources.getMessage(locale, key)).andReturn("this_is_the_result");

        Assert.assertEquals(MessagesUtil.getMessage(
                        request, key, CustomerManagementConstants.BUNDLE_NAME),
                "this_is_the_result");
    }
}

我得到了这个例外

java.lang.IllegalStateException: missing behavior definition for the preceding method call:
HttpServletRequest.getAttribute("CustomerManagementResources")
Usage is: expect(a.foo()).andXXX()
    at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:42)
    at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:85)
    at com.sun.proxy.$Proxy10.getSession(Unknown Source)

但我正在设置' getAttribute(" CustomerManagementResources")'测试设置中的字段。

注意 - 我尝试添加

replay();

在我调用目标方法之前,但没有区别。

1 个答案:

答案 0 :(得分:3)

因此,经过一些工作后,EasyMock异常消息“previous”可以被认为是“下一个”方法调用。

(Locale)request.getSession()

下一次打电话给我的班级我想要嘲笑。将此期望添加到我的测试中解决了问题

expect(request.getSession()).andReturn(session).anyTimes();