Gwt 如何使用HttpRequestSession模拟RemoteServiceServlet
下面是我的RemoteServiceServlet的代码片段。函数getSubject()从HttpServletRequest获取会话,HttpServletRequest引用getThreadLocalRequest。我正在做一个junit测试来测试这个服务器,但是getThreadLocalRequest没有被填充并且返回nullGwt 如何使用HttpRequestSession模拟RemoteServiceServlet,gwt,junit,Gwt,Junit,下面是我的RemoteServiceServlet的代码片段。函数getSubject()从HttpServletRequest获取会话,HttpServletRequest引用getThreadLocalRequest。我正在做一个junit测试来测试这个服务器,但是getThreadLocalRequest没有被填充并且返回null public class Server extends XsrfProtectedServiceServlet implements RemoteInterfa
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失败,因为会话未填充。如何模拟服务器以便填充会话。您需要使用模拟框架来围绕被测对象创建行为。我将PowerMock与EasyMock()一起使用 不过,我建议您首先从构造函数中重构代码。正如所写的,这段代码测试起来非常复杂,因为getResourceAsStream方法是底层类类型的静态方法。由于它没有在被测试的方法中使用(数据库引用也没有),我质疑是否需要使用构造函数来获取资源包 要测试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 );
}
}