How to test Controller with Junit?

Asked

Viewed 259 times

0

I’m testing the URL like this

package br.com.aluguel.de.carros.unidade.usuario;

import br.com.aluguel.de.carros.endereco.Endereco;
import br.com.aluguel.de.carros.usuario.Usuario;
import br.com.aluguel.de.carros.usuario.UsuarioService;
import org.hamcrest.core.Is;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import java.util.Optional;

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class TestaUsuarioController {
    @Autowired
    MockMvc mvc;

    @Autowired
    UsuarioService service;

    @Test
    public void testaUrlUsuario() throws Exception{
        Endereco e = new Endereco();
        e.setComplemento("complemento 1");
        e.setId(1l);
        e.setBairro("bairro 2");
        e.setCidade("cidade 3");
        e.setEstado("estado 4");
        e.setLogradouro("logradouro 5");
        e.setNumero(6);

        Usuario u = new Usuario();
        u.setPerfil("cliente");
        u.setId(1l);
        u.setNome("Arthur");
        u.setCnh("000");
        u.setCpf("111");
        u.setEmail("[email protected]");
        u.setEndereco(e);
        u.setSenha("senha 2");
        u.setTelefone("4678612");

        given(service.usuario(1l)).willReturn(Optional.of(u));
        mvc.perform(get("/usuario").contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.u", Is.is(u.getPerfil())));
    }
}

He returns me Nullpointerexception

java.lang.NullPointerException
    at br.com.aluguel.de.carros.unidade.usuario.TestaUsuarioController.testaUrlUsuario(TestaUsuarioController.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Pointing out an error on line 48 which is my Given:

given(service.usuario(1l)).willReturn(Optional.of(u));

Someone saves me??!!

  • You’ll only get to use @Autowired when there is a Spring context created, I suggest following some tutorial to use @SpringBootTest for example, missing settings for your test to work.

1 answer

0

Arthur, put @Mockbean instead of @Autowired on your service. You won’t be able to mock it with Autowired

Also puts these Annotations at the top of your test class that are necessary to climb the contexts that Mockmvc needs to run:

@Runwith(Mockitojunitrunner.Cass) @Enableautoconfiguration @Webmvctest(Yourcontroller.class)

Browser other questions tagged

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