简体   繁体   中英

MockHttpServletResponse body empty

I try to test my method addPerson() in my controller, but when I execute the test I have status 200 with an empty body in MockHttpServletResponse . I would like to test the body response with jsonPath from MockMvcResultMatchers but I can't do it while the body is empty.

Here is my test:

@WebMvcTest(PersonController.class)
@ExtendWith(SpringExtension.class)
public class PersonControllerTest {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private Model model;

    @MockBean
    private PersonService service;

     @Test
     public void addPersonTest() throws Exception {
        this.mvc.perform(post("/person/add")
            .contentType(MediaType.APPLICATION_JSON).content("{\"firstName\": \"Test\",\"lastName\": \"\",\"address\": \"\",\"city\": \"\",\"zip\": \"\",\"phone\": \"\",\"email\": \"\"}"))
            .andDo(MockMvcResultHandlers.print())
            .andExpect(status().isOk());
     }

Here is my controller with the method addPerson()

@RequestMapping("/person")
@RestController
public class PersonController {

    @Autowired
    Model model;

    private static final Logger logger = LogManager.getRootLogger();

    @Autowired
    private PersonService personService;

    @GetMapping("/")
    public List<Person> allPerson() {
        return personService.all();
    }

    @PostMapping("/add")
    public List<Person> addPerson(@RequestBody Person person) {
        List<Person> listPerson = this.personService.add(person);

        logger.info("Request = @RequestBody = {}", person);
        logger.info("Response {}", listPerson);
        return listPerson;
    }

And here is the service:

@Service
public class PersonService {

    @Autowired
    private Model model;

    public PersonService(Model model2) {
         this.model = model2;
    }

    public List<Person> add(Person person) {
        List<Person> listPersons = model.getPersons();
        listPersons.add(person);
        return listPersons;
    }

Thanks for your help.

As you mock the PersonService you have to provide its behaviour otherwise it always returns null . You can use when().thenReturn() from Mockito for this:

@WebMvcTest(PersonController.class)
@ExtendWith(SpringExtension.class)
public class PersonControllerTest {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private Model model;

    @MockBean
    private PersonService service;


     @Test
     public void addPersonTest() throws Exception {

           List<Person> personList = Arrays.asList(new Person()); // create list here
           when(service.add(any(Person.class)).thenReturn(personList); // mock the behaviour of your PersonService bean

           this.mvc.perform(post("/person/add")
            .contentType(MediaType.APPLICATION_JSON).content("{\"firstName\": \"Test\",\"lastName\": \"\",\"address\": \"\",\"city\": \"\",\"zip\": \"\",\"phone\": \"\",\"email\": \"\"}"))
            .andDo(MockMvcResultHandlers.print())
                    .andExpect(status().isOk());
     }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM