簡體   English   中英

如何在帶有驗證注釋的 bean 屬性的測試用例中引發 ConstraintValidationException?

[英]How to raise a ConstraintValidationException in a test case for bean properties with validation annotations?

我正在嘗試測試我的 bean 是否具有正確的驗證注釋。 我正在使用 spring-boot。 這是一個示例測試用例:

package com.example.sandbox;

import static org.assertj.core.api.Assertions.assertThatThrownBy;

import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.validation.annotation.Validated;

@SpringBootTest
class ValidationTest {

    @Test
    void testConstructor() {
        TestedBean bean = new TestedBean(null);

        assertThatThrownBy(() -> checkIfValidated(bean)).isInstanceOf(ConstraintViolationException.class);
    }

    @Test
    void testSetter() {
        TestedBean bean = new TestedBean(null);

        assertThatThrownBy(() -> bean.setSomeProperty(null)).isInstanceOf(ConstraintViolationException.class);
    }

    private void checkIfValidated(@Valid TestedBean bean) {

    }

    @Validated
    class TestedBean {
        @NotNull
        private String someProperty;

        public TestedBean(String someProperty) {
            super();
            this.someProperty = someProperty;
        }

        public String getSomeProperty() {
            return someProperty;
        }

        public void setSomeProperty(@NotNull String someProperty) {
            this.someProperty = someProperty;
        }
    }
}

我希望調用checkIfvalidated()setSomeProperty(null)來引發ConstraintViolationException ,並且測試能夠通過,但它們都失敗了:

java.lang.AssertionError: 
Expecting code to raise a throwable.
    at com.example.sandbox.ValidationTest.test(ValidationTest.java:20)
    ...

我的 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>com.example.springbootsandbox</artifactId>
    <version>0.0</version>
    <name>SpringBootSandbox</name>
    <description>Sandbox for Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.1.5.Final</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

為什么這里沒有引發ConstraintViolationException bean 屬性有一個@NotNull注釋,bean 本身是@Validated並且方法簽名需要一個@Valid bean。

有沒有一種簡單的方法可以在我的測試 class 的上下文中引發該異常?

當我在服務接口的方法簽名上使用驗證注釋時,一切都按預期工作。 我不明白區別在哪里。

服務接口:

package com.example.sandbox;

import javax.validation.constraints.NotNull;

import org.springframework.validation.annotation.Validated;

@Validated
public interface IService {
    public void setValue(@NotNull String value);
}

服務實現:

package com.example.sandbox;

import org.springframework.stereotype.Service;

@Service
public class SomeService implements IService {
    @Override
    public void setValue(String value) {
        // Do nothing
    }
}

測試用例:

package com.example.sandbox;

import static org.assertj.core.api.Assertions.assertThatThrownBy;

import javax.validation.ConstraintViolationException;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SomeServiceTests {
    @Autowired
    IService service;

    @Test
    void testSetValue() {
        assertThatThrownBy(() -> service.setValue(null)).isInstanceOf(ConstraintViolationException.class);
    }
}

==> 測試通過。


根據給定答案的工作代碼:

測試 class:

@SpringBootTest
class ValidationTest {
    @Autowired
    private Validator validator; // Using the default validator to test property annotations

    @Autowired
    private TestedBeanService service; // Using a service to test method annotations

    @Test
    void testPropertyAnnotations() {
        TestedBean bean = new TestedBean(null);
        Set<ConstraintViolation<TestedBean>> violations = validator.validate(bean);
        assertThat(violations).isNotEmpty();
    }

    @Test
    void testMethodAnnotations() {
        TestedBean bean = new TestedBean(null);
        assertThatThrownBy(() -> service.setBeanProperty(bean, null)).isInstanceOf(ConstraintViolationException.class);
    }
}

被測試的bean:

@Validated
class TestedBean {
    @NotNull
    private String someProperty;

    public TestedBean(String someProperty) {
        super();
        this.someProperty = someProperty;
    }

    public String getSomeProperty() {
        return someProperty;
    }

    public void setSomeProperty(String someProperty) { // No more annotation on setter
        this.someProperty = someProperty;
    }
}

服務接口:

@Validated
public interface TestedBeanService {
    // method annotation on the interface method
    void setBeanProperty(TestedBean bean, @NotNull String someProperty);
}

服務實現:

@Service
public class TestedBeanServiceImpl implements TestedBeanService {

    @Override
    public void setBeanProperty(TestedBean bean, String someProperty) {
        bean.setSomeProperty(someProperty);
    }
}

為什么這里沒有引發ConstraintViolationException bean 屬性有一個@NotNull注釋,bean 本身是@Validated並且方法簽名需要一個@Valid bean。

注釋本身沒有任何意義,它們應該以某種方式處理。 在這種情況下,@Validated 注釋由@Validated為其 beans處理。 該測試不是 Spring bean,因此框架不查看與驗證相關的注釋,因此也不例外。

即使測試是 Spring Bean,該方法也可能無法開箱即用。 有關詳細信息,請參閱問題。

有沒有一種簡單的方法可以在我的測試 class 的上下文中引發該異常?

看看這個問題

當我在服務接口的方法簽名上使用驗證注釋時,一切都按預期工作。 我不明白區別在哪里。

發生這種情況是因為service是 Spring bean,但測試不是。 service上的方法被調用時,它會被MethodValidationInterceptor攔截,這不是測試的情況

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM