【问题标题】:Set up JUnit test database设置 JUnit 测试数据库
【发布时间】:2012-07-26 02:54:21
【问题描述】:
void insertAllRecords(){
    insertRecord("tom", 100);
    insertRecord("jake", 200);
    insertRecord("tim", 300);
    insertRecord("andy", 400);
    insertRecord("mike", 500);
}

我正在写 JUnit 测试以测试具有测试数据库的东西。它从一个空数据库开始。 我想测试不同的东西,但我不想用相同的参数重复insertRecord

有没有一种简单的方法来指定执行哪一行?比如我只想在@test函数之一中添加tom和andy。

我知道在每种测试方法中,数据库都从 0 开始。 我希望能够:

  • 在 testA 中,使用 tom 和 jake 设置 db。
  • 在 testB 中,使用 andy 设置 db 还有迈克。
  • 在 testC 中,使用所有这些设置 db。

但我不想在每个测试中都放置单独的插入语句。我希望能够使用一些参数调用 insertAllRecords。

谢谢

【问题讨论】:

  • 在集成测试中,您应该在测试完成后回滚数据库记录。这样,您就不必担心重复。
  • 我可能每列都有几个数组,并有一个循环来添加我想要的数组。有更好的方法吗?
  • 你为什么不模拟你的数据?类似mockito的东西......

标签: java database unit-testing testing junit


【解决方案1】:

据我所知,JUnit 不支持您想要的行为。您可能想看看TestNG,它允许使用@BeforeMethod@AfterMethod 注释进行测试特定设置。它还允许使用带有@Parameter@DataProvider 注释的参数化数据进行更灵活的测试数据。

【讨论】:

    【解决方案2】:

    使用抽象方法 abstract void insertAllRecords(); 将您的 Junit 类转换为抽象类

    然后在你需要的情况下扩展这个类。例如

    class TestWithTomClass extends AbstractTestClass{
        public void insertAllRecords(){
           insertRecord("tom", 100);
        }
    
        @Test
        public void myTestWithTom(){
           ....
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      相关资源
      最近更新 更多