我有一个问题一直没能解决。我目前正在用Spring Boot构建一个Rest Api,我想在服务层内部验证我的用户实体。我尝试过不同的方法,但目前没有成功。在我的测试中,当它到达create方法时,不会抛出异常。
这是我当前的代码:
用户实体
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Email(message = "User needs a valid Mail.")
@Column(unique = true, nullable = false)
private String mail;
@NotBlank
@Column(nullable = false)
private String lastName;
@NotBlank
@Column(nullable = false)
private String firstName;
}
用户服务
@Service
@RequiredArgsConstructor
public class UserService implements IUserService {
private final UserRepository userRepository;
@Override
public User create(@Valid User user) {
user.setId(null);
User createdUser = userRepository.save(user);
return createdUser;
}
我的测试
@SpringBootTest
class UserServiceTest {
@Mock
UserRepository userRepository;
@InjectMocks
UserService userService;
@Test
void createUserFailsBecauseNoFirstName() {
User testUser = new User("test@mail.de", "LastName", "FirstName");
when(userRepository.save(any(User.class))).thenReturn(testUser);
testUser.setFirstName(null);
Assertions.assertThrows(ConstraintViolationException.class,
() -> userService.create(testUser));
}
pom.xml
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.rest</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<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-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
我尝试过的:
- @已验证服务类(我遵循的教程(
- @在方法层面进行额外验证
- 删除@Validated&验证并使用Validator,但它不会被注入(遵循该教程(
因为您使用@InjectMocks
来获取UserService
,所以它不是由Spring管理的bean,因为@InjectMocks
是Mockito注释,对Spring一无所知,也不知道如何从Spring容器中获取bean。因此,您现在实际上正在测试一个非springUserService
bean,因此不会进行验证。
更改为使用@Autowired
从Spring容器中获取UserService
bean,并使用@MockBean
将Spring容器中的UserRepository
bean替换为模拟版本。此外,您还需要在UserService
上添加@Validated
:
@Service
@Validated
public class UserService implements IUserService {
}
@SpringBootTest
class UserServiceTest {
@MockBean
UserRepository userRepository;
@Autowired
UserService userService;
@Test
void createUserFailsBecauseNoFirstName() {
User testUser = new User("test@mail.de", "LastName", "FirstName");
when(userRepository.save(any(User.class))).thenReturn(testUser);
testUser.setFirstName(null);
Assertions.assertThrows(ConstraintViolationException.class,
() -> userService.create(testUser));
}
}
这并不是我正在寻找的解决方案,但即使在新的Spring Boot项目中,我也无法将其用于Annotations。所以我现在在我的服务中使用了一个验证器,让它验证我的用户。
服务
@Service
@RequiredArgsConstructor
public class UserService implements IUserService {
private final Validator validator;
private final UserRepository userRepository;
@Override
public User create(User user) {
user.setId(null);
// new Validation
Set<ConstraintViolation<T>> violations = validator.validate(objectToValidate);
if (!violations.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (ConstraintViolation<T> constraintViolation : violations) {
sb.append(constraintViolation.getMessage());
}
throw new ResourceValidationException("Error occurred: " + sb.toString());
}
User createdUser = userRepository.save(user);
return createdUser;
}
测试
@SpringBootTest
class UserServiceTest {
@Mock
UserRepository userRepository;
@Autowired
Validator validator;
UserService userService = new UserService(validator, userRepository);
@Test
void createUserFailsBecauseNoFirstName() {
User testUser = new User("test@mail.de", "LastName", "FirstName");
when(userRepository.save(any(User.class))).thenReturn(testUser);
testUser.setFirstName(null);
Assertions.assertThrows(ConstraintViolationException.class,
() -> userService.create(testUser));
}
由于我总是得到一个没有验证的验证器bean(所以我的测试没有抛出预期的错误(,而且我不想创建ValidatorFactory,所以我还添加了一个保存ValidatorBean的配置。
配置
@Configuration
public class AppConfig {
@Bean
public Validator defaultValidator() {
return new LocalValidatorFactoryBean();
}
}