[英]How to use correctly MockMvc to test post method in Junit?
I am unit testing with MockMvc for the first time and I have not figured it out yet how to use it correctly.我是第一次使用 MockMvc 进行单元测试,但我还没有弄清楚如何正确使用它。 I am trying to test a simple POST method.
我正在尝试测试一个简单的 POST 方法。 My code (class code) works good, I tested it with postman, so clearly the problem is with the testing code.
我的代码(类代码)运行良好,我用 postman 对其进行了测试,很明显问题出在测试代码上。
Controller: Controller:
@Controller
@RequestMapping("/employees")
public class EmployeeController {
private final EmployeeService employeeService;
private final EmployeeModelAssembler assembler;
@Autowired
public EmployeeController(EmployeeService employeeService, EmployeeModelAssembler assembler){
this.employeeService = employeeService;
this.assembler = assembler;
}
@PostMapping()
public ResponseEntity<?> addEmployee(@RequestBody Employee employee, UriComponentsBuilder builder){
EntityModel<Employee> entityModel = this.assembler.toModel(this.employeeService.addEmployee(employee));
return ResponseEntity.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri()).body(entityModel);
}
...
There are more methods above, but addEmployee is the method i am trying to test.上面还有更多方法,但 addEmployee 是我要测试的方法。
Test:测试:
@ExtendWith(SpringExtension.class)
@WebMvcTest(EmployeeController.class)
@AutoConfigureMockMvc
public class EmployeeControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private EmployeeService employeeService;
@MockBean
private EmployeeModelAssembler assembler;
@InjectMocks
private EmployeeController employeeController;
@Before
public void setUp(){
MockitoAnnotations.openMocks(this);
}
@Test
public void testAddEmployee() throws Exception {
String mockEmployeeJson =
" \"firstName\": \"new\",\n" +
" \"lastName\": \"Employee\",\n" +
" \"emailAddress\": \"new@Employee.com\",\n" +
" \"roll\": \"Software Engineer\",\n" +
" \"team\": \n" +
" {\n" +
" \"teamId\": 1\n" +
" }\n" +
"}";
mockMvc.perform(MockMvcRequestBuilders.post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(mockEmployeeJson)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
output: output:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /employees
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"171"]
Body = "firstName": "new",
"lastName": "Employee",
"emailAddress": "new@Employee.com",
"roll": "Software Engineer",
"team":
{
"teamId": 1
}
}
Session Attrs = {}
Handler:
Type = com.Ventura.Notifier.controller.EmployeeController
Method = com.Ventura.Notifier.controller.EmployeeController#addEmployee(Employee, UriComponentsBuilder)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.http.converter.HttpMessageNotReadableException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 400
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status expected:<200> but was:<400>
Expected :200
Actual :400
<Click to see difference>
Edit 1 changed the test to:编辑 1将测试更改为:
private Employee employee;
@BeforeEach
public void setUpEmployee(){
Team team = new Team();
team.setTeamId(1);
employee = new Employee();
employee.setTeam(team);
employee.setRoll("software developer");
employee.setLastName("Levi");
employee.setEmailAddress("a@a.com");
employee.setFirstName("David");
}
@Test
public void testAddEmployee() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
mockMvc.perform(MockMvcRequestBuilders.post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(employee))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
but I am getting a null pointer exception.但我收到 null 指针异常。
Edit 2编辑 2
I solved the null pointer exception, not sure why though.我解决了 null 指针异常,但不确定为什么。 if anyone is interested in the solution:
如果有人对解决方案感兴趣:
The test:考试:
@Test
public void testAddEmployee() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
mockMvc.perform(MockMvcRequestBuilders.post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(employee))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is2xxSuccessful());
}
and i changed the return statement in the addEmployee method to:我将 addEmployee 方法中的 return 语句更改为:
return new ResponseEntity<>(entityModel, HttpStatus.CREATED);
Your JSON formated input request body is incorrectly formatted, I will recommend using Map
with objectMapper
, Map.of is from jdk-9 if you are using lower version you can replacse it by creating another map using new
keyword您的 JSON 格式的输入请求正文格式不正确,我建议将
Map
与objectMapper
一起使用,Map.of 来自 jdk-9 如果您使用的是较低版本,则可以通过使用new
关键字创建另一个 map 来替换它
@Test
public void testAddEmployee() throws Exception {
Map<String,Object> body = new HashMap<>();
body.put("firstName","new");
body.put("lastName","Employee");
body.put("emailAddress","new@Employee.com");
body.put("roll","Software Engineer");
body.put("team",Map.of("teamId",1));
mockMvc.perform(MockMvcRequestBuilders.post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeAsString(body))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
Your posted body is not actually a JSON. Try using an ObjectMapper (eg from Jackson) to convert your DTO to a string which can be send with MockMvc:您发布的正文实际上不是 JSON。尝试使用 ObjectMapper(例如来自 Jackson)将您的 DTO 转换为可以使用 MockMvc 发送的字符串:
Employee dto = new Employee()
// properly set your fields
[...]
mockMvc.perform(MockMvcRequestBuilders.post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeAsString(dto))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.