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

sqougxex  于 5个月前  发布在  Spring
关注(0)|答案(3)|浏览(59)

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

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中对产品进行测试。

@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 should be greater than zero”的消息输出。我试图做的是创建一个对象,然后使用值进行Assert,使其失败或工作,如assertEquals(hello,objectCreated.getName());任何建议或帮助都将受到高度赞赏。

xqnpmsa8

xqnpmsa81#

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

iugsix8n

iugsix8n2#

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

private static Validator validator;

@BeforeAll
static void beforeAll() {
    try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
        validator = factory.getValidator();
    }
}

字符串

ffscu2ro

ffscu2ro3#

只需使用模型的setter

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

字符串

相关问题