Issue
Here, I'm trying to perform a unit test on the endpoint /persons
:
@AutoConfigureMockMvc
@WebMvcTest(PersonController.class)
public class PersonServiceTest {
@Autowired
private static MockMvc mockMvc;
@MockBean
private PersonService personService;
@Test
public void shouldGetPersons() throws Exception {
Person person = new Person();
person.setFirstName("Harry");
person.setLastName("POTTER");
List<Person> persons = new ArrayList<>();
persons.add(person);
Mockito.when(personService.getPersons()).thenReturn(persons);
mockMvc.perform(get("/persons")).andExpect(status().isOk());
}
}
I've checked the stack trace but I do not understand why it might my test end up on a NullPointerException
.
Stack trace
@RestController
public class PersonController {
@Autowired
private PersonService personService;
@GetMapping("/persons")
public List<Person> getPersons() throws IOException {
return personService.getPersons();
}
}
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
public List<Person> getPersons() {
return personRepository.findAll();
}
}
Solution
I didn't notice that my mockMvc
was static
by mistake. Removing that solved the problem!
@Autowired
private static MockMvc mockMvc;
To
@Autowired
private MockMvc mockMvc;
Answered By - d0750926