我有以下单元测试:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {EqualblogApplication.class})
@WebAppConfiguration
@TestPropertySource("classpath:application-test.properties")
public class PostServiceTest {
// ...
@Test(expected = ConstraintViolationException.class)
public void testInvalidTitle() {
postService.save(new Post()); // no title
}
}
save
中的PostService
代码为:
public Post save(@Valid Post post) {
return postRepository.save(post);
}
Post
类在大多数字段中都标有@NotNull
。
问题是:没有抛出验证异常。
然而,这只发生在测试中。 使用该应用程序通常会运行验证并抛出异常。
注意:我想自动(保存时)而不是手动验证然后保存(因为它更现实)。
答案 0 :(得分:3)
此解决方案适用于Spring 5.它也适用于Spring 4。 (我已经在Spring 5和SpringBoot 2.0.0上测试了它。)
有三件事需要:
像这样:
@TestConfiguration
static class TestContextConfiguration {
@Bean
public MethodValidationPostProcessor bean() {
return new MethodValidationPostProcessor();
}
}
像这样:
@Validated
class PostService {
public Post save(@Valid Post post) {
return postRepository.save(post);
}
}
MethodValidationPostProcessor documentation
中的更多详情希望有所帮助
答案 1 :(得分:0)
这是我通过将 select
t.teamid, t.teamName, EmployeeIdentity, e.employeeid, e.emplyeename
from
Employee e
join
(select
TeamId, Employeeid, 'Team Member' as EmployeeIdentity
from TeamMember
union all
select teamid, TeamLeaderId, 'Team Leader' as EmployeeIdentity
from team) as tm on tm.employeeid = e.employeeid
join
teams t on tm.TeamId = t.TeamId
加载到上下文中来做到的:
ValidationAutoConfiguration.class
和 MyComponent 类:
@SpringBootTest
@ContextConfiguration(classes = { MyComponent.class, ValidationAutoConfiguration.class
public class MyComponentValidationTest {
@Autowired
private MyComponent myComponent;
@Test
void myValidationTest() {
String input = ...;
// static import from org.assertj.core.api.Assertions
assertThatThrownBy(() -> myComponent.myValidatedMethod(input))
.isInstanceOf(ConstraintViolationException.class)
.hasMessageContaining("my error message");
}
}