如何将 HttpServletRequest 对象传递到测试用例?

2022-09-01 06:22:47

现在我正在编写类的测试用例。我想将 HttpServletRequest 对象参数传递给我的测试用例方法,以检查该方法是否正常工作。所以任何人都给我这个建议。

public void testCheckBatchExecutionSchedule() throws Exception
    {
        assertTrue("Batch is Completed :", returnPointsRatingDisputeFrom.checkBatchExecutionSchedule(request));
    }

答案 1

Spring提供了一个名为MockHttpServletRequest的类,可用于测试需要HttpServletRequest的代码。

public void testCheckBatchExecutionSchedule() throws Exception
{
   MockHttpServletRequest request = new MockHttpServletRequest();
   request.addParameter("parameterName", "someValue");
   assertTrue("Batch is Completed :", returnPointsRatingDisputeFrom.checkBatchExecutionSchedule(request));
}

答案 2

您应该使用模拟库模拟请求对象,例如 http://code.google.com/p/mockito/

public void testCheckBatchExecutionSchedule() throws Exception
{
   HttpServletRequest mockRequest = mock(HttpServletRequest.class);
   //setup the behaviour here (or do it in setup method or something)
   when(mockRequest.getParameter("parameterName")).thenReturn("someValue");
   assertTrue("Batch is Completed :", returnPointsRatingDisputeFrom.checkBatchExecutionSchedule(mockRequest));
}

推荐