service层vaild
时间: 2024-01-11 15:54:30 浏览: 81
在原来的项目中,@Valid和@Validated注解通常被用于controller层对requestBody参数进行校验。但是现在项目决定将controller层变薄,将requestBody的校验移至service层。然而,发现在service层的单元测试中,这两个注解并没有生效。为了解决这个问题,可以按照以下步骤进行操作:
1. 首先,在service类上添加@Validated注解,例如:
```
@Service
@Validated
public class StorageBinServiceImpl implements StorageBinService {
// ...
}
```
2. 然后,在单元测试类中添加@RunWith(SpringJUnit4ClassRunner.class)和@ContextConfiguration(classes = {UserServiceTest.Config.class})注解,例如:
```
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {UserServiceTest.Config.class})
public class UserServiceTest {
// ...
}
```
3. 接着,在单元测试类中创建一个内部静态类Config,用于配置MethodValidationPostProcessor,并且在该类中注入service bean,例如:
```
public static class Config {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
@Bean
public UserService userService() {
return new UserService();
}
}
```
4. 最后,在单元测试方法上使用@Test注解,并调用service的方法进行测试,例如:
```
@Autowired
private UserService service;
@Test
public void should_throw_exception_when_age_smaller_than_zero() {
CreateUserCommand command = new CreateUserCommand("deigo", -1);
try {
service.save(command);
} catch (ConstraintViolationException e) {
System.out.println(e.getConstraintViolations().size());
// 输出结果应为1
}
}
```
通过以上步骤,可以在service层的单元测试中使@Validated注解生效,实现对requestBody参数的校验。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [解决 @Validate 在 Service 层的单元测试不生效](https://blog.csdn.net/yy_diego/article/details/116611840)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [JAVA参数分组验证Validation及service层触发校验规则](https://blog.csdn.net/Seven71111/article/details/112175646)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文