¿Cómo simular el HttpServletRequest? [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Tengo una función que busca un parámetro de consulta y devuelve un booleano:

  public static Boolean getBooleanFromRequest(HttpServletRequest request, String key) {
        Boolean keyValue = false;
        if(request.getParameter(key) != null) {
            String value = request.getParameter(key);
            if(keyValue == null) {
                keyValue = false;
            }
            else {
                if(value.equalsIgnoreCase("true") || value.equalsIgnoreCase("1")) {
                    keyValue = true;
                }
            }
        }
        return keyValue;
    }

Tengo a junit y easymock en mi pom.xml, ¿cómo hago para burlarme de HttpServletRequest ?

Author: Blankman, 2012-10-18

5 answers

HttpServletRequest es muy similar a cualquier otra interfaz, por lo que puede burlarse de ella siguiendo el EasyMock Readme

Aquí hay un ejemplo de cómo probar unitariamente su método getBooleanFromRequest

// static import allows for more concise code (createMock etc.)
import static org.easymock.EasyMock.*;

// other imports omitted

public class MyServletMock
{
   @Test
   public void test1()
   {
      // Step 1 - create the mock object
      HttpServletRequest req = createMock(HttpServletRequest.class);

      // Step 2 - record the expected behavior

      // to test true, expect to be called with "param1" and if so return true
      // Note that the method under test calls getParameter twice (really
      // necessary?) so we must relax the restriction and program the mock
      // to allow this call either once or twice
      expect(req.getParameter("param1")).andReturn("true").times(1, 2);

      // program the mock to return false for param2
      expect(req.getParameter("param2")).andReturn("false").times(1, 2);

      // switch the mock to replay state
      replay(req);

      // now run the test.  The method will call getParameter twice
      Boolean bool1 = getBooleanFromRequest(req, "param1");
      assertTrue(bool1);
      Boolean bool2 = getBooleanFromRequest(req, "param2");
      assertFalse(bool2);

      // call one more time to watch test fail, just to liven things up
      // call was not programmed in the record phase so test blows up
      getBooleanFromRequest(req, "bogus");

   }
}
 9
Author: Guido Simone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-20 07:11:48

Use algún framework burlón e. g. Mockito o JMock que viene con la capacidad de burla de tales objetos.

En Mockito, puedes hacer burla como:

 HttpServletRequest  mockedRequest = Mockito.mock(HttpServletRequest.class);

Para más detalles sobre el Mockito, ver: ¿Cómo lo bebo? en el sitio de Mockito.

En JMock, puedes hacer burla como:

 Mockery context = new Mockery();
 HttpServletRequest  mockedRequest = context.mock(HttpServletRequest.class);

Para obtener más información sobre JMock, consulte: JMock-Primeros pasos

 14
Author: Yogendra Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-01 00:08:12

Este es un hilo antiguo ... pero la pregunta sigue siendo relevante.

Otra buena opción es MockServiceRequest y MockServiceResponse en el marco de primavera:

Http://docs.spring.io/spring/docs/2.0.x/api/org/springframework/mock/web/package-summary.html

 10
Author: FoggyDay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-23 04:55:45

No conozco easymock, pero el libro 'Unit Testing in Java: How Tests Drive the Code' de Johannes Link contenía explicaciones de cómo probar Servlets usando una biblioteca que construiría de objetos ficticios.

El sitio acompañante para el libro ahora se ha ido (cambio en la editorial de algo...) pero el sitio complementario de la publicación original alemana todavía está en funcionamiento. Desde él, puede descargar las definiciones de todos los objetos ficticios.

 2
Author: Richard JP Le Guen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-18 01:59:44

Echa un vistazo a Mockrunner: http://mockrunner.sourceforge.net /

Tiene muchos simulacros de Java EE fáciles de usar, incluyendo HttpServletRequest y HttpServletResponse.

 0
Author: mbelow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-20 10:27:36