如何使用HttpRequestSession模拟RemoteServiceServlet

时间:2014-01-28 20:05:56

标签: gwt junit

这是我的RemoteServiceServlet的代码片段。函数getSubject()从HttpServletRequest获取会话,该会话引用getThreadLocalRequest。我正在进行junit测试以测试此服务器,但getThreadLocalRequest未填充并返回null。

public class Server extends XsrfProtectedServiceServlet implements RemoteInterface {

private static final long serialVersionUID = 2230123191888380541L;


public Server() throws IOException
{
    credentials = new PropertiesCredentials(Server.class.getResourceAsStream("AwsCredentials.properties.email"));
    database = new Database();
}

public Subject getSubject()
{
    HttpServletRequest request = this.getThreadLocalRequest();
    HttpSession session = request.getSession(false);

    Subject subject = (Subject)session.getAttribute("subject");
    return subject;
}
}

这是我的junit测试

@Test
public void testserver()
{
    Server  s = new Server();
    s.getSubject();
}

s.getSubject失败,因为未填充会话。如何模拟服务器以便我可以填充会话。

1 个答案:

答案 0 :(得分:1)

您需要使用模拟框架来创建围绕被测对象的行为。我将PowerMock与EasyMock(http://code.google.com/p/powermock/)一起使用。

我建议你先做的是从构造函数中重构代码。如上所述,此代码的测试非常复杂,因为getResourceAsStream方法是底层Class类型的静态方法。由于它未在测试方法中使用(也不是数据库引用),我质疑是否需要使用构造函数来获取资源包。

要测试你的getSubject()方法,你需要做的就是创建一个类部分模拟的实例,其中getThreadLocalRequest是唯一被模拟的方法:

@RunWith( PowerMockRunner.class )
@PrepareForTest( Server.class )
public class ServerTest {
    @Test
    public void testGetSubjectReturnsSubjectFromHttpSession() {
       // assuming the constructor is cleaned up, create a Server instance...
       Server server = PowerMock.createPartialMockAndInvokeDefaultConstructor( Server.class, "getThreadLocalRequest" );

       // create a mock object that represents the Http request
       HttpServletRequest mockRequest = PowerMock.createMock(HttpServletRequest.class);
       EasyMock.expect( server.getThreadLocalRequest() ).andReturns( mockRequest);

       // create a mock for the Http Session
       HttpSession mockSession = PowerMock.createMock( HttpSession.class );

       EasyMock.expect( mockRequest.getSession( EasyMock.anyBoolean() ) ).andReturns( mockSession );
       EasyMock.expect( mockSession.getAttribute( EasyMock.isA( String.class ) ).andReturns( mockSubject );

       // put the mocks into playback mode
       PowerMock.replayAll();

       // exercise the method
       Subject subject = server.getSubject();

       // verify that the mocks were called as you expect them to be...
       PowerMock.verifyAll();

       // and here you put other assertions that relate to the data returned...
       Assert.assertNotNull( subject );
   }
}