How to test the creation of an obj and method call in a Servlet?

Asked

Viewed 500 times

0

I’m trying to create a web application using TDD, however, I’m having a question of how to test the Servlet that processes requests and calls due logic, I don’t know how to do the assert.

@Test
public void deveCriarInstaciarUmObjetoActionPelaURI() throws ServletException, IOException {
    Dispatcher dispatcher = new Dispatcher();

    HttpServletRequest request = Mockito.mock( HttpServletRequest.class );
    HttpServletResponse response = Mockito.mock( HttpServletResponse.class);

    Mockito.when( request.getContextPath() ).thenReturn( "/app" );
    Mockito.when( request.getRequestURI() ).thenReturn(  "/app/controle/acao" );

    dispatcher.service(request , response);

}

I would need to test if a Control object was created and called the action method, but I don’t know how to do this test, any suggestion?

1 answer

1

According to the Documentation:

-Create a mock of your object to be tested Controle.class, for example:

@Mock  
Controle controle;

-In your test start and check if the method acao was called:

public void deveCriarInstaciarUmObjetoActionPelaURI(){
   MockitoAnnotations.initMocks(this);
   ...
   verify(controle).acao();
   ...
}

That is what you seek ?. Anything is just return.

Hugs

  • the problem is that I do not want to bang(?!?) the control, I would like to test if it was instantiated within the service and a method of his was called, to test this way, so I tried I would have to create a control attribute in the Servlet and divide in two methods, one that would return an instance of control and another that would call the method, and test the two things separately, I thought it got kind of strange

  • The problem is: if your Control is a local variable or if it is private, Voce will have to change the structure of your code in order to be testable. NOTE: I never worked with TDD, but I’ve used Mockito in some projects. As far as my knowledge goes, in this case I advise you to take a look at Powermockito, it makes it possible to test local and static variables.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.