简体   繁体   English

EasyMock处理HttpSession

[英]EasyMock handling HttpSession

How do I get EasyMock to work with HttpSession. 如何让EasyMock与HttpSession一起使用。 I'm doing the following: 我正在做以下事情:

    System.out.println("begin");
    HttpServletRequest request = createMock(HttpServletRequest.class);
    expect(request.getParameter("firstName")).andReturn("o");
    expect(request.getAttribute("lastName")).andReturn("g");
    request.setAttribute("lastName", "g");   

    HttpSession session = createMock(HttpSession.class);
    expect(session.getAttribute("testAttribute")).andReturn("testValue");
    session.setAttribute("testAttribute", "testValue");  //appears to not matter

    replay(request);
    replay(session);

    System.out.println("param: "+request.getParameter("firstName"));
    System.out.println("attribute: "+request.getAttribute("lastName"));
    System.out.println("before session");
    if(session.getAttribute("testAttribute")!=null){    
        System.out.println("fired session");
        System.out.println((String)session.getAttribute("testAttribute"));
    }

    System.out.println("after session");
    System.out.println("end");

The following is my output: begin 以下是我的输出:开始
param: o param:o
attribute: g 属性:g
before session 在会议之前
fired session 解雇会议

Any Help would be greatly appreciated! 任何帮助将不胜感激! Thank you in advance 先感谢您

Your question is quite badly worded and your code example is far from how mocks are usually used. 您的问题措辞非常严重,您的代码示例与通常使用的模拟方式相差甚远。 However, given the benefit of the doubt, I'm assuming you're wanting to know why your test doesn't get past the if block. 但是,鉴于怀疑的好处,我假设您想知道为什么您的测试没有通过if块。

It is essentially because you've called session.getAttribute("testAttribute") twice, but only expected it once. 这主要是因为你已经两次调用了session.getAttribute("testAttribute") ,但只预期了一次。

So, you have this following expectation: 所以,你有以下期望:

expect(session.getAttribute("testAttribute")).andReturn("testValue");

But, then you have this block: 但是,你有这个块:

if(session.getAttribute("testAttribute")!=null){
    System.out.println("fired session");
    System.out.println((String)session.getAttribute("testAttribute"));
}

So you need to expect the call twice, since you call it twice. 所以你需要两次调用,因为你调用它两次。 There are a number of ways to do this. 有很多方法可以做到这一点。 Any of the following would work: 以下任何一种都可以:

  1. Using the times(int) method. 使用times(int)方法。
  2. Using the anyTimes() method. 使用anyTimes()方法。
  3. Calling the expectation multiple times. 多次呼唤期望。

Here are examples of each of those options. 以下是每个选项的示例。

1. expect(session.getAttribute("testAttribute")).andReturn("testValue").times(2);

2. expect(session.getAttribute("testAttribute")).andReturn("testValue").anyTimes();

3. expect(session.getAttribute("testAttribute")).andReturn("testValue");
   expect(session.getAttribute("testAttribute")).andReturn("testValue");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM