Вопрос

How do I get EasyMock to work with 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
attribute: 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.

It is essentially because you've called session.getAttribute("testAttribute") twice, but only expected it once.

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.
  2. Using the anyTimes() method.
  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 с атрибуция
Не связан с StackOverflow
scroll top