[英]how to do unit test validation annotations in spring
我在諸如
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進行測試。
@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以及如何測試消息輸出“ ... number應該大於零”。 我試圖做的是創建一個對象,然后使用使它失敗或起作用的值進行斷言,例如assertEquals(hello,objectCreated.getName());。 任何建議或幫助將不勝感激。
要驗證bean批注,您必須在執行中具有上下文。 您可以執行以下操作:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
然后您的測試將驗證注釋。
但是,如果您只想驗證模型的注釋(沒有其他業務規則),則可以使用驗證器:
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());
}
只需使用模型的設置器
ProductModel productModel = new ProductModel();
productModel.setQuantity("a crazy String");
productModel.setAnotherValueOfThatModel(true);
productController.createProduct(new ProductModel(), mockBindingResult);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.