Spring的测试注释@Sql如何表现得像@BeforeClass?

时间:2017-12-12 14:56:59

标签: java spring junit spring-test

如何告诉@Sql注释只针对课程运行一次,而不是针对每个@Test方法运行?

@BeforeClass具有相同的行为?

@org.springframework.test.context.jdbc.Sql(
     scripts = "classpath:schema-test.sql",
     executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD
)
public class TestClass {
      @Test
      public void test1() {
        //runs the @Sql script
      }

      @Test
      public void test2() {
        //runs the @Sql script again
      }
}

5 个答案:

答案 0 :(得分:2)

你无法做到开箱即用。 @Sql annotation只有two modes - BEFORE_TEST_METHODAFTER_TEST_METHOD

负责执行这些脚本的监听器SqlScriptsTestExecutionListener不会在类之前或类之后的方法中实现。

要解决此问题,我将实现自己的TestExecutionListener,包装默认的SqlScriptsTestExecutionListener。然后,您可以在测试中声明使用新的侦听器而不是旧的侦听器。

public class BeforeClassSqlScriptsTestExecutionListener implements TestExecutionListener
{    
    @Override
    public void beforeTestClass(final TestContext testContext) throws Exception
    {
        // Note, we're deliberately calling beforeTest*Method*
        new SqlScriptsTestExecutionListener().beforeTestMethod(testContext);
    }

    @Override
    public void prepareTestInstance(final TestContext testContext) { }

    @Override
    public void beforeTestMethod(final TestContext testContext) { }

    @Override
    public void afterTestMethod(final TestContext testContext) { }

    @Override
    public void afterTestClass(final TestContext testContext) { }
}

您的测试将成为:

@TestExecutionListeners(
    listeners = { BeforeClassSqlScriptsTestExecutionListener.class },
    /* Here, we're replacing more than just SqlScriptsTestExecutionListener, so manually
       include any of the default above if they're still needed: */
    mergeMode = TestExecutionListeners.MergeMode.REPLACE_DEFAULTS
)
@org.springframework.test.context.jdbc.Sql(
    scripts = "classpath:schema-test.sql",
    executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD
)
public class MyTest
{
    @Test
    public void test1() { }

    @Test
    public void test2() { }
}

答案 1 :(得分:2)

@BeforeAll 和 @BeforeClass 注释需要“静态”方法。所以它不起作用。 配置文件中的@PostConstruct 怎么样?它对我很好。

@TestConfiguration
public class IntegrationTestConfiguration {

@Autowired
private DataSource dataSource;

@PostConstruct
public void initDB() throws SQLException {
    try (Connection con = dataSource.getConnection()) {
        ScriptUtils.executeSqlScript(con, new ClassPathResource("data.sql"));
    }
}
}

@ContextConfiguration(classes = {IntegrationTestConfiguration.class})
public class YourIntegrationTest {

}

答案 2 :(得分:0)

由于IllegalStateException中的getTestMethod()方法,此代码引发了DefaultTestContext.java(春季5.0.1):

public final Method getTestMethod() {
    Method testMethod = this.testMethod;
    Assert.state(testMethod != null, "No test method");
    return testMethod;
}

在通过建议的实现调用beforeTestClass方法时,textContext不包含有效的testMethod(在此阶段是正常的):

public class BeforeClassSqlScriptsTestExecutionListener implements TestExecutionListener {

    @Override
    public void beforeTestClass(TestContext testContext) throws Exception {
        new SqlScriptsTestExecutionListener().beforeTestMethod(testContext);
    }
}

执行负责运行SQL脚本的代码(在SqlScriptsTestExecutionListener中)时,需要有效的testMethod

Set<Sql> sqlAnnotations = AnnotatedElementUtils.getMergedRepeatableAnnotations(
            testContext.getTestMethod(), Sql.class, SqlGroup.class);

我最终使用了这种解决方法:

@Before
public void setUp() {
    // Manually initialize DB as @Sql annotation doesn't support class-level execution phase (actually executed before every test method)
    // See https://jira.spring.io/browse/SPR-14357
    if (!dbInitialized) {
        final ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
        resourceDatabasePopulator.addScript(new ClassPathResource("/sql/[...].sql"));
        resourceDatabasePopulator.execute(dataSource);
        dbInitialized = true;
    }
    [...]
}

答案 3 :(得分:0)

对于JUnit 5,直接的干净 解决方案

@MyInMemoryDbConfig
//@Sql(value = {"/appconfig.sql", "/album.sql"}) -> code below is equivalent but at class level
class SomeServiceTest {
    @BeforeAll
    void setup(@Autowired DataSource dataSource) {
        try (Connection conn = dataSource.getConnection()) {
            // you'll have to make sure conn.autoCommit = true (default for e.g. H2, in memory)
            // e.g. url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1;MODE=MySQL
            ScriptUtils.executeSqlScript(conn, new ClassPathResource("appconfig.sql"));
            ScriptUtils.executeSqlScript(conn, new ClassPathResource("album.sql"));
        }
    }
    // your @Test methods follow ...

但是当您的数据库连接未配置autoCommit = true时,您必须将所有内容包装在事务中:

@RootInMemoryDbConfig
@Slf4j
class SomeServiceTest {
    @BeforeAll
    void setup(@Autowired DataSource dataSource,
            @Autowired PlatformTransactionManager transactionManager) {
        new TransactionTemplate(transactionManager).execute((ts) -> {
            try (Connection conn = dataSource.getConnection()) {
                ScriptUtils.executeSqlScript(conn, new ClassPathResource("appconfig.sql"));
                ScriptUtils.executeSqlScript(conn, new ClassPathResource("album.sql"));
                // should work without manually commit but didn't for me (because of using AUTOCOMMIT=OFF)
                // I use url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1;MODE=MySQL;AUTOCOMMIT=OFF
                // same will happen with DataSourceInitializer & DatabasePopulator (at least with this setup)
                conn.commit();
            } catch (SQLException e) {
                SomeServiceTest.log.error(e.getMessage(), e);
            }
            return null;
        });
    }
    // your @Test methods follow ...

为什么清洁 解决方案

因为根据Script Configuration with @SqlConfig

  

@Sql和@SqlConfig提供的配置选项是   等效于ScriptUtils和   ResourceDatabasePopulator,但它们是由    XML名称空间元素。

奖金

您可以将此方法与其他@Sql声明混合使用。

答案 4 :(得分:0)

对于JUnit 5,我通过adrhc来获得第二个解决方案。

对于Junit 4,您可以执行以下操作:

@Autowired
private DataSource database;

private static boolean dataLoaded = false;

    @Before
    public void setup() throws SQLException {
        if(!dataLoaded) {
            try (Connection con = database.getConnection()) {
                ScriptUtils.executeSqlScript(con, new ClassPathResource("path/to/script.sql"));
                dataLoaded = true;
            }
        }
    }

(同样,假设您的连接有autoCommit=true,请参阅adrhc的帖子。)

如果打算并行运行测试,则需要用AtomicBoolean替换布尔值。