在Spring Boot中将每个测试类的liquibase文件与测试数据分开

时间:2019-02-21 11:35:59

标签: spring-boot testing annotations liquibase spring-aop

我想为特定测试分离测试数据。例如,我们有两个测试类A和B,它们分别在不同的数据上运行,因此我想创建 ATestData.xml和BTestData.xml,当测试类启动时,应执行ATestData.xml,然后回滚,然后启动测试B,执行BTestData.xml。 在Arquillian Persistence Extension中,有@UsingDataSet("datasets/users.yml")

我开始写自己的注释:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface LiquibaseTestDataFile {
    String value() default "";
}

@Slf4j
@Aspect
@Component
public class LiquibaseTestDataFileAspect {

    @Before("execution(* (@LiquibaseTestDataFile *).*(..)) || execution(@LiquibaseTestDataFile * *(..))")
    public void insertTestData(JoinPoint joinPoint){
    log.info("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB");

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> declaringClass = signature.getMethod().getDeclaringClass();
        LiquibaseTestDataFile myAnnotation = declaringClass.getAnnotation(LiquibaseTestDataFile.class);

       //TODO if null maybe on method

       //log.info(myAnnotation.value());
    }
}

但是当注释在测试类上时,它不会触发。

我在配置中使用@EnableAspectJAutoProxy

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TransferManagerRestApplication.class})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

在测试课中。

1 个答案:

答案 0 :(得分:0)

我已经找到了使用@PostConstruct

的解决方案
@Component
public class LiquibaseDataTestConfiguration {

    @Autowired
    private SpringLiquibase springLiquibase;

    public void insert(String fileName){
        try {
            Connection connection = springLiquibase.getDataSource().getConnection();
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
            Liquibase liquibase = new liquibase.Liquibase(fileName, new ClassLoaderResourceAccessor(), database);
            liquibase.update(new Contexts(springLiquibase.getContexts()), new LabelExpression(springLiquibase.getLabels()));
        } catch (LiquibaseException | SQLException e) {
            e.printStackTrace();
        }
    }
}

和测试班

@Autowired
private LiquibaseDataTestConfiguration liquibaseDataTestConfiguration;

@PostConstruct
public void initData(){
    liquibaseDataTestConfiguration.insert("liquibase/AClassTest.xml");
}