我尝试在我的 Controller 中测试我的方法 addPerson()
,但是当我执行测试时,我在 MockHttpServletResponse
中有一个空主体的状态 200。我想用 MockMvcResultMatchers
中的 jsonPath
测试主体响应,但主体为空时无法执行此操作。
这是我的测试:
@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());
}
这是我的 Controller ,方法是 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;
}
这是服务:
@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;
}
感谢您的帮助。
最佳答案
当您模拟 PersonService
时,您必须提供它的行为,否则它总是返回 null
。为此,您可以使用 Mockito 中的 when().thenReturn()
:
@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());
}
}
关于java - MockHttpServletResponse 主体为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60805398/