【发布时间】:2018-08-27 10:34:24
【问题描述】:
我正在编写集成测试来测试我的端点,并且需要在构建后立即在数据库中设置一个用户,以便 Spring Security Test 注释 @WithUserDetails 有一个用户可以从数据库中收集。
我的班级设置是这样的:
@RunWith(value = SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@WithUserDetails(value = "email@address.com")
public abstract class IntegrationTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private Service aService;
@PostConstruct
private void postConstruct() throws UserCreationException {
// Setup and save user data to the db using autowired service "aService"
RestAssuredMockMvc.mockMvc(mockMvc);
}
@Test
public void testA() {
// Some test
}
@Test
public void testB() {
// Some test
}
@Test
public void testC() {
// Some test
}
}
然而,@PostConstruct 方法会为 每个 注释的 @Test 调用,即使我们没有再次实例化主类。
因为我们使用 Spring Security Test (@WithUserDetails),所以我们需要在使用 JUnit 注释 @Before 之前将用户持久化到数据库中。我们也不能使用@BeforeClass,因为我们依赖@Autowired 服务:aService。
我找到的一个解决方案是使用一个变量来确定我们是否已经设置了数据(见下文),但这感觉很脏,并且会有更好的方法。
@PostConstruct
private void postConstruct() throws UserCreationException {
if (!setupData) {
// Setup and save user data to the db using autowired service "aService"
RestAssuredMockMvc.mockMvc(mockMvc);
setupData = true;
}
}
【问题讨论】:
标签: java spring spring-boot junit4 spring-test