【问题标题】:TestNG: How to skip @BeforeMethod call for some testsTestNG:如何跳过 @BeforeMethod 调用某些测试
【发布时间】:2013-12-16 06:43:37
【问题描述】:

我正在使用 TestNG 进行单元测试。我正在使用 @BeforeMethod 保存记录,然后执行更新、搜索、删除测试。

我正在寻找可以避免对某些测试用例执行 @BeforeMethod 方法调用的选项。例如,我有三个测试保存、更新和删除。在这种情况下,我只想调用 @BeforeMethod 进行更新和删除测试,而不是保存测试。有什么想法吗?

请注意,我不想使用 @DependesOnMethods,因为不推荐。

提前致谢。

我的测试类如下所示:

@ContextConfiguration("file:application-context-test.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class MyEntityTest {

    int long myEntityId; 

    @BeforeMethod 
    public saveRecord(){
      session=getCurrentSessionFactory()
      myEntity = new myEntity();
      myEntityId = session.save(myEntity)
    }

    @Test
    public saveTest(){
      session=getCurrentSession()
      myEntity =session.getByID(myEntityId)
      session.save(myEntity)
    }

    @Test
    public updateTest(){
      session=getCurrentSession()
      myEntity =session.getByID(myEntityId)
      session.update(myEntity)
    }
}

【问题讨论】:

    标签: java unit-testing testng


    【解决方案1】:

    TestNG 支持一些参数的本地注入,例如有关要调用的方法的信息。所以你可以使用以下方法:

    import java.lang.reflect.Method;
    ...
    @BeforeMethod 
    public saveRecord(Method method){
      if (!method.getName().equals("saveTest")) {
        session=getCurrentSessionFactory()
        myEntity = new myEntity();
        myEntityId = session.save(myEntity)
      }
    }
    

    http://testng.org/doc/documentation-main.html#native-dependency-injection

    【讨论】:

      【解决方案2】:

      您可以在测试中分组,它会为不同的组调用单独的 beforeMethod http://testng.org/doc/documentation-main.html#test-groups

      【讨论】:

      • 根据本页说明testng.org/javadoc/org/testng/annotations/BeforeMethod.html"对于before方法(beforeSuite、beforeTest、beforeTestClass和beforeTestMethod,但不包括beforeGroups):如果alwaysRun设置为true,则无论什么都将运行此配置方法它所属的组。”这意味着 @BeforeMethod 属于一个组将始终被调用,即使该组未被调用进行测试。
      • 如果你使用 alwaysRun 你是在强制它执行。通过调用测试方法中注释为@beforeMethod 的方法进行简单的代码重构。
      • 如果@beforeMethod使用简单,我该如何给这个方法的组名。此外,alwaysRun 默认为 true。即使它不属于该组,它也会始终执行
      • 您可以通过删除您要使用的测试用例中带注释的@BeforeMethod 来调用特定方法,否则您可以通过此 beforeMethod 调用来监听。 AlwaysRun 默认为 false grepcode.com/file/repo1.maven.org/maven2/org.testng/testng/6.8/…
      • 您能否提供一个链接,让听众可以绕过这个@beforeMethod 调用实现?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 2016-05-27
      相关资源
      最近更新 更多