我在弹簧控制器中使用@MockMvc测试,但是我有一个问题。 MockMvc测试未通过方法时如何处理消息错误。
实体:
@Entity
@ApiModel(description = "All details about the Product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO,generator = "system-uuid")
@GenericGenerator(name = "system-uuid",strategy = "uuid2")
private String id;
@NotNull(message = "name can not null")
@ApiModelProperty(notes = "The name is product")
private String name;
@ApiModelProperty(notes = "The type is product")
private String type;
@NotNull(message = "category can not null")
private String category;
private String description;
private Double prince;
public Product() {
}
public Product(String name, String type, String category, String description, Double prince) {
this.name = name;
this.type = type;
this.category = category;
this.description = description;
this.prince = prince;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrince() {
return prince;
}
public void setPrince(Double prince) {
this.prince = prince;
}
@Override
public String toString() {
return "Product{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", type='" + type + '\'' +
", category='" + category + '\'' +
", description='" + description + '\'' +
", prince=" + prince +
'}';
}
}
StudentController:
@RestController
@RequestMapping("/products")
public class ProductController {
@PostMapping
public ResponseEntity<ProductDto> createProduct(@RequestBody Product product) {
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(product.getId()).toUri();
return ResponseEntity.created(location).body(productService.createProduct(product));
}
}
在上述实体中,我想使用@MockMvc测试createProduct。如果产品中的名称为null,我想在@MockMvc中显示消息。看起来像:“名称不能为空”。如果通过,我不想展示它。吼叫我的测试:
@Test
public void givenProductURIWithPost_whenMockMVC_thenVerifyResponse() {
this.mockMvc.perform(post("/products")).andDo(print())
.andExpect(status().isOk()).andExpect(content()
.contentType("application/json;charset=UTF-8"))
}
我有两个问题:
1.How to show message "name can not null" if name in product is
null in @mockmvc.
2. If my project in 20 field in Products entity : Example: name,category.. I can test sequence field in Products or only test
one time contain all field.