我在类中有一些注释,例如
public class ProductModel {
@Pattern(regexp="^(1|[1-9][0-9]*)$", message ="Quantity it should be number and greater than zero")
private String quantity;
Run Code Online (Sandbox Code Playgroud)
然后在我的控制器中
@Controller
public class Product Controller
private ProductService productService;
@PostMapping("/admin/product")
public String createProduct(@Valid @ModelAttribute("product") ProductModel productModel, BindingResult result)
{
// add println for see the errors
System.out.println("binding result: " + result);
if (!result.hasErrors()) {
productService.createProduct(productModel);
return "redirect:/admin/products";
} else {
return "product";
}
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试从 ProductController 测试 createProduct。
@RunWith(MockitoJUnitRunner.class)
public class ProductControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
ProductService productService;
@InjectMocks …Run Code Online (Sandbox Code Playgroud) spring unit-testing spring-mvc mockito hibernate-annotations