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

问题描述 投票:0回答:2

我在类中有一些注释

 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());任何建议或帮助将受到高度赞赏。

spring unit-testing spring-mvc mockito hibernate-annotations
2个回答
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());
}

0
投票

只需使用模型的setter

ProductModel productModel = new ProductModel();
productModel.setQuantity("a crazy String");
productModel.setAnotherValueOfThatModel(true);
productController.createProduct(new ProductModel(), mockBindingResult);
© www.soinside.com 2019 - 2024. All rights reserved.