如何在 spring 中进行单元测试验证注释 [英] how to do unit test validation annotations in spring
问题描述
我在类中有一些注释,例如
I have some annotation in a class such as
public class ProductModel {
@Pattern(regexp="^(1|[1-9][0-9]*)$", message ="Quantity it should be number and greater than zero")
private String quantity;
然后在我的控制器中
@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";
}
}
然后我尝试从 ProductController 中测试 createProduct.
Then I am trying to do a test of createProduct from ProductController.
@RunWith(MockitoJUnitRunner.class)
public class ProductControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
ProductService productService;
@InjectMocks
ProductController productController;
@Mock
private BindingResult mockBindingResult;
@Before
public void setupTest() {
MockitoAnnotations.initMocks(this);
Mockito.when(mockBindingResult.hasErrors()).thenReturn(false);
}
@Test
public void createProduct() throws Exception {
productController = new ProductController(productService);
productController.createProduct(new ProductModel(), mockBindingResult);
这里我不知道如何向对象 productmodel 添加值,也不知道如何测试...数字应该大于零"的消息输出.我试图做的是创建一个对象,然后用值断言使其失败或工作,例如assertEquals(你好,objectCreated.getName());任何建议或帮助将不胜感激.
Here I do not know how can I add values to the object productmodel and also how can I test the message output of "...number should be greater than zero". What I was trying to do it was create an object and then assert with values for making it fail or work such as assertEquals(hello,objectCreated.getName()); Any advice or help will be highly appreciated.
推荐答案
要验证 bean 注释,您必须具有正在执行的上下文.你可以这样做:
To validate bean annotations you must have the context in execution. You can do this with:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
然后您的测试将验证注释.
Then your tests will validate the annotations.
但是,如果您只想验证模型的注释(没有其他业务规则),您可以使用验证器:
However, if you just want to validate the annotation of model (without another business rules) you can use a validator:
private static ValidatorFactory validatorFactory;
private static Validator validator;
@BeforeClass
public static void createValidator() {
validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}
@AfterClass
public static void close() {
validatorFactory.close();
}
@Test
public void shouldReturnViolation() {
ProductModel productModel = new ProductModel();
productModel.setQuantity("a crazy String");
Set<ConstraintViolation<ProductModel>> violations = validator.validate(productModel);
assertFalse(violations.isEmpty());
}
这篇关于如何在 spring 中进行单元测试验证注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!