【问题标题】:Load SQL database before each test每次测试前加载 SQL 数据库
【发布时间】:2023-03-24 19:42:01
【问题描述】:

请有人帮我解决以下问题。有什么方法可以从 sql 数据文件中加载数据库?在我的测试中,我使用的是 dbunit。我通常只是在我的本地 mysql 服务器上创建新的数据库模式,然后将所有数据加载到这个模式中,然后像这样在 java 中测试它

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:context/DAOTestContext.xml")
public class HistoricalDataDAOTest {

private final Integer id = 66124;
private final Integer startDate = 20140101;
private final Integer endDate = 20140102;

@Autowired
private HistoricalDataDAO histDataDAO;

public HistoricalDataDAOTest() {
}

@BeforeClass

public static void setUpClass() {

}

@AfterClass
public static void tearDownClass() {
}

@Before

public void setUp() {
}

@After
public void tearDown() {
}

@Test

public void getTest() {
    List portions = histDataDAO.get("ing", startDate, endDate);
    System.out.println(portions);
    assertNotNull(portions);

}

@Test
public void getByOrderIdTest() {

    List<HistoricalPortions> h = histDataDAO.getByOrderId(id);
    assertNotNull(h);
}

}

但我需要在每次测试之前从 sql 文件加载数据库,我的意思是我想将数据库从 sql 文件加载到空的数据库模式中。在 dbunit 中有类似的东西 @DatabaseSetup("test_db.sql"),但我认为这不适用于 sql 文件。 请问有什么办法吗?

【问题讨论】:

    标签: java mysql junit4 spring-test


    【解决方案1】:

    由于您使用的是 Spring,因此您可以在 @Before 方法中使用 ScriptUtils

    Connection connection = dataSource.getConnection();
    ScriptUtils.executeSqlScript(connection, new ClassPathResource("test_db.sql"));
    

    【讨论】:

    • 您好,很抱歉很久才回答。感谢您的解决方案,它帮助我解决了部分问题。
    【解决方案2】:

    我更喜欢executing SQL scripts declaratively with @Sql

    @Sql("/test_db.sql")
    @Transactional
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:context/DAOTestContext.xml")
    public class HistoricalDataDAOTest {
    ...
    }
    

    我还建议在您的测试中使用@Transactional。这将导致对您的数据库的任何更改都回滚。它可以在类或方法级别应用。

    手册中关于此的章节 - https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-executing-sql

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 2015-05-01
      • 2013-07-15
      • 2013-11-08
      相关资源
      最近更新 更多