【问题标题】:how to do unit test validation annotations in spring如何在春季进行单元测试验证注释
【发布时间】:2019-03-15 15:38:11
【问题描述】:

我在一个类中有一些注释,例如

 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 添加值,也不知道如何测试“...数字应大于零”的消息输出。 我试图做的是创建一个对象,然后用值断言使其失败或工作,例如 assertEquals(你好,objectCreated.getName()); 任何建议或帮助将不胜感激。

【问题讨论】:

    标签: spring unit-testing spring-mvc mockito hibernate-annotations


    【解决方案1】:

    要验证 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());
    }
    

    【讨论】:

    • 嗨,Allan,是的,我意识到我必须做 IT 来验证我的注释是否有效。感谢您的帮助!
    【解决方案2】:

    只需使用模型的设置器

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

    【讨论】:

      猜你喜欢
      • 2019-01-24
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      相关资源
      最近更新 更多