I'm trying test a RestAPI in Java, but I can't mock my Service class
When start test, it gives me an error: java.lang.NullPointerException: Cannot invoke "com.tcc.tccbackend.services.PacienteService.findById(java.lang.Integer)" because "this.service" is null
.
Code:
@WebMvcTest(PacienteController.class)
public class PacienteTest extends BaseTest {
@Mock
private PacienteService service;
@Autowired
private MockMvc mockMvc;
@BeforeEach
public void setup() {
RestAssuredMockMvc.mockMvc(mockMvc);
}
@Test
@DisplayName("Retorna sucesso quando busca um paciente ")
public void t4() {
Mockito.when(service.findById(9999))
.thenReturn(new Paciente(9999, "Gilberson", "gilber@gmail.com", "68211836104", "(67) 99625-5371", new Date(), List.of()));
RestAssuredMockMvc
.given()
.header("Authorization", getJWT())
.accept(ContentType.JSON)
.when()
.get("/pacientes/9999")
.then().statusCode(200);
}
BaseTest.class:
public class BaseTest {
public BaseTest(){
baseURI = "http://localhost";
port = 8080;
basePath = "/api";
}
public static String getJWT() {
return given()
.body("{\n" + "\t\"email\": \"paula@gmail.com\",\n" + "\t\"senha\": \"senha\"\n" + "}")
.contentType(ContentType.JSON)
.when()
.post("/user/login")
.then()
.extract()
.path("token");
}
}
Versions:
Your mixing up unit test and integration test config.
Annotations for unit tests look like this:
@ExtendWith(MockitoExtension.class)
class MyTest {
@Mock
private ServiceA myMock;
@Spy
private ServiceB mySpy;
@InjectMocks
private ServiceC myClassUnderTest;
@Test
void receive() {
// test logic
}
}
Annotations for integration tests look like this:
@ActiveProfiles("test")
@SpringBootTest
class MyTest {
@MockBean
private ServiceA myMock;
@SpyBean
private ServiceB mySpy;
@Autowired
private ServiceC myClassUnderTest;
@Test
void receive() {
// test logic
}
}
I don't know about your test config because you didn't post it here, but I suppose you should use @MockBean
instead of @Mock
for PacienteService service
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.