如何在春季进行单元测试验证注释



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

 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(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);

最新更新