我在类中有一些注释,例如
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);
在这里,我不知道如何向对象产品模型添加值,也不知道如何测试“...数字应该大于零”的消息输出。
我想做的是创建一个对象,然后用值断言使其失败或工作,例如
assertEquals(你好,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());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)