Home > Uncategorized > Testear la salida de un servlet

Testear la salida de un servlet

A veces me ha interesado saber que es lo que se escribe en la respuesta de un servlet, por ejemplo cuando quieres comprobar JSON. Con este pequeño ejemplo podemos analizar el objeto “buffer” para comprobar que se ha escrito lo que esperabamos a cada test:

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

public class MyTest {

   @Mock
   private HttpServletRequest request;
   @Mock
   private HttpServletResponse response;

   private StringBuffer buffer;

   @Before
   public void before() throws IOException{
      MockitoAnnotations.initMocks(this);
      PrintWriter writer = mock(PrintWriter.class);
      when(response.getWriter()).thenReturn(writer);
      buffer=new StringBuffer();
      doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
               char[] chars=(char[])invocation.getArguments()[0];
               int init=(Integer)invocation.getArguments()[1];
               int end=(Integer)invocation.getArguments()[2];
               for(int i=init;i<end;i++){
                  buffer.append(chars[i]);
               }
               return null;
            }
      }).when(writer).write(any(char[].class), anyInt(), anyInt());
   }

}

El objeto buffer tendra el valor de lo que se haya escrito en el response.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: