Unit Test Controller Spring with Mockito

Asked

Viewed 705 times

1

I’m trying to test the method below my controller:

    @RequestMapping(value = "/listar", method = RequestMethod.GET)
        public ModelAndView iniciaTela(ModelAndView model, HttpServletRequest request){

            final ParametroEnvioManualVO parametroEnvioManualVO =  new ParametroEnvioManualVO();
            final PerfilUsuarioLogadoVO perfilUsuarioLogado = (PerfilUsuarioLogadoVO) request
                    .getSession().getAttribute(AbstractConstantes.PERFIL_USUARIO_LOGADO);
            String strCodigoUnidadeUsuario = perfilUsuarioLogado.getNuUnidade();

            parametroEnvioManualVO.setCodigoUnidadeUsuario(strCodigoUnidadeUsuario);
            parametroEnvioManualVO.setNomeUnidadeUsuario(perfilUsuarioLogado.getSgUnidade());
            List<ModeloMensagemUnidadeVO> listaModelos = bean.obterModelosAutorizadosUnidade(Integer.parseInt(strCodigoUnidadeUsuario));
            parametroEnvioManualVO.setListaModelos(listaModelos);

            model.addObject(SESSION_ATTRIBUTES, parametroEnvioManualVO);
            model.setViewName(VIEW_NAME);
            return model;
        }

However, I am not able to simulate an Httpsession to pass the profileUsuarioLogized object, as it is from it that the controller searches for a parameter to query models and return to the model. I’m trying with Mockito, but I’m banging my head here.... My challenge is to mount Httpservletrequest with an Httpsession inside and inside the profileUsuarioLog as parameter.

Thanks in advance!

1 answer

1


To perform the unit test you can use the classes Mockhttpservletrequest and Mockhttpsession spring.

To get the idea, follow a simple controller:

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController(value = "/test")
public class TestController {

    @GetMapping(value = "/list")
    public ModelAndView list(ModelAndView model, HttpServletRequest request) {
        model.addObject("returnedAttribute", request.getSession().getAttribute("test"));
        return model;
    }
}

Here I’m just taking the attribute test of the session and resetting in the model as returnedAttribute

I will do a simple unit test to validate that the value that was initially passed in the session was returned in the model:

import static org.junit.jupiter.api.Assertions.assertEquals;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.web.servlet.ModelAndView;

@ExtendWith(MockitoExtension.class)
public class TestControllerTest {

    @Test
    public void list() {
        ModelAndView modelAndView = new ModelAndView();
        ModelAndView returnedModel = controller.list(modelAndView, getMockServletRequest());
        assertEquals("nullptr user on StackOverflow", returnedModel.getModelMap().get("returnedAttribute"));
    }

    private HttpServletRequest getMockServletRequest() {
        MockHttpServletRequest mockRequest = new MockHttpServletRequest();
        mockRequest.setSession(getMockSession());
        return mockRequest;
    }

    private HttpSession getMockSession() {
        MockHttpSession mockSession = new MockHttpSession();
        mockSession.setAttribute("test", "nullptr user on StackOverflow");
        return mockSession;
    }

    @InjectMocks
    private TestController controller;
}

With that we have a test passing:

inserir a descrição da imagem aqui

  • Thanks man. But I’m getting this error below when trying to instantiate Mockhttpservletrequest():

  • If you can supplement the question with your pom.xml, seems to be a problem related to a libs conflict, night put my pom.xml for you to take a look

  • It was the same mistake I was facing here before opening the topic. The following link is the pom: https://github.com/andreluizpb/geral/blob/master/pom.xml

  • The error is this: java&#xA;java.lang.NoSuchMethodError: org.springframework.util.StreamUtils.emptyInput()Ljava/io/InputStream;&#xA; at org.springframework.mock.web.MockHttpServletRequest.<clinit>(MockHttpServletRequest.java:102)&#xA; at xxx.controller.ManterEnvioManualControllerTest.getMockServletRequest(ManterEnvioManualControllerTest.java:110)&#xA;

  • 1

    I think there is room for a new question to resolve this conflict of versions, since the original question has already been answered

Browser other questions tagged

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