如何在Spring中进行单元测试验证注解

sqougxex  于 2024-01-05  发布在  Spring
关注(0)|答案(3)|浏览(163)

我在一个类中有一些注解,

  1. public class ProductModel {
  2. @Pattern(regexp="^(1|[1-9][0-9]*)$", message ="Quantity it should be number and greater than zero")
  3. private String quantity;

字符串
然后在我的控制器里

  1. @Controller
  2. public class Product Controller
  3. private ProductService productService;
  4. @PostMapping("/admin/product")
  5. public String createProduct(@Valid @ModelAttribute("product") ProductModel productModel, BindingResult result)
  6. {
  7. // add println for see the errors
  8. System.out.println("binding result: " + result);
  9. if (!result.hasErrors()) {
  10. productService.createProduct(productModel);
  11. return "redirect:/admin/products";
  12. } else {
  13. return "product";
  14. }
  15. }


然后,我尝试从ProductController中对产品进行测试。

  1. @RunWith(MockitoJUnitRunner.class)
  2. public class ProductControllerTest {
  3. @Autowired
  4. private MockMvc mockMvc;
  5. @Mock
  6. ProductService productService;
  7. @InjectMocks
  8. ProductController productController;
  9. @Mock
  10. private BindingResult mockBindingResult;
  11. @Before
  12. public void setupTest() {
  13. MockitoAnnotations.initMocks(this);
  14. Mockito.when(mockBindingResult.hasErrors()).thenReturn(false);
  15. }
  16. @Test
  17. public void createProduct() throws Exception {
  18. productController = new ProductController(productService);
  19. productController.createProduct(new ProductModel(), mockBindingResult);


在这里我不知道如何向对象productmodel中添加值,也不知道如何测试“. number should be greater than zero”的消息输出。我试图做的是创建一个对象,然后使用值进行Assert,使其失败或工作,如assertEquals(hello,objectCreated.getName());任何建议或帮助都将受到高度赞赏。

xqnpmsa8

xqnpmsa81#

要验证bean注解,你必须有执行中的上下文。你可以这样做:

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

字符串
然后您的测试将验证注解。
但是,如果你只是想验证模型的注解(没有其他业务规则),你可以使用验证器:

  1. private static ValidatorFactory validatorFactory;
  2. private static Validator validator;
  3. @BeforeClass
  4. public static void createValidator() {
  5. validatorFactory = Validation.buildDefaultValidatorFactory();
  6. validator = validatorFactory.getValidator();
  7. }
  8. @AfterClass
  9. public static void close() {
  10. validatorFactory.close();
  11. }
  12. @Test
  13. public void shouldReturnViolation() {
  14. ProductModel productModel = new ProductModel();
  15. productModel.setQuantity("a crazy String");
  16. Set<ConstraintViolation<ProductModel>> violations = validator.validate(productModel);
  17. assertFalse(violations.isEmpty());
  18. }

展开查看全部
iugsix8n

iugsix8n2#

除了Allan Moreira Leite的答案,您还可以通过使用一个beforeAll()方法来使测试设置更加简洁:

  1. private static Validator validator;
  2. @BeforeAll
  3. static void beforeAll() {
  4. try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
  5. validator = factory.getValidator();
  6. }
  7. }

字符串

ffscu2ro

ffscu2ro3#

只需使用模型的setter

  1. ProductModel productModel = new ProductModel();
  2. productModel.setQuantity("a crazy String");
  3. productModel.setAnotherValueOfThatModel(true);
  4. productController.createProduct(new ProductModel(), mockBindingResult);

字符串

相关问题