【问题标题】:TestNG: Identifying which tests methods are nextTestNG:确定下一个测试方法
【发布时间】:2011-01-18 05:17:20
【问题描述】:

我的目标是在每个测试方法之后清除()我的 javax.persistence.EntityManager。

这是一个测试类的例子:

public class Example
{
    @Test(dataProvider = "sampleDataProvider")
    public void testA(String parameter)
    {
        System.out.println(parameter);
    }

    @Test(dataProvider = "sampleDataProvider")
    public void testB(String parameter)
    {
        System.out.println(parameter);
    }
}

entityManager 在 dataProvider "sampleDataProvider" 中使用,通过查询 DB 中的测试数据,然后以这种格式编译:new Object[2][1]。请记住,数据的查询和编译都是在测试方法(使用@DataProvider 注释)实际运行之前完成的,我们实际上是在查询实体而不仅仅是字符串。

上面的测试类会这样运行:

testA("some queried entity 1")
testA("some queried entity 2")
testB("some queried entity 1")
testB("some queried entity 2")

我最初的解决方案是使用@AfterTest 注释来清除entityManager。但是,它会在testAtestB 的第二次运行(或第二次测试实例)之前将"some queried entity 2" 从 entityManager 中分离出来,这会导致"some queried entity 2" 成员的读/写操作出现问题。

我的目标是在测试方法之后清除 entityManager,而不一定在测试方法的每个实例之后。

TestNG 是否可以知道接下来要运行哪个测试?这样,如果下一个测试是新测试,我可以轻松清除 entityManager。

还有其他建议吗?

【问题讨论】:

    标签: java testng entitymanager


    【解决方案1】:

    我不知道有什么简单的方法可以得到下一个测试方法。顺便说一句,您可以使用 @AfterGroups 注释获得相同的结果:

    @Test(groups = {"groupA"})
    public void testA(...) { ... }
    
    @Test(groups = {"groupB"})
    public void testB(...) { ... }
    
    @AfterGroups(groups = {"groupA"})
    public void afterGroupA() {
        // clear entity manager here
    }
    

    请注意,TestNG 不保证测试的开始顺序,除非您使用 @Test 注释的 dependsOnMethods 或 dependsOnGroups 参数,或 testng.xml 文件中标记的“preserve-order”属性明确指定它。

    更新

    您也可以使用自己的TestListiner。您可以实现onTestStart() 方法,如果需要,它会进行清除。 AFAIU,调用的测试方法在部分填充的 ITestResult 中可用。顺便说一句,小心 - 这可能会导致由隐式测试逻辑引起的问题(从测试代码中看不到清除)。

    【讨论】:

    • 谢谢。我想过这个。但是,我们有大量的测试和数据提供者,必须将它们全部分组是一项非常困难的任务。我了解 TestNG 以随机顺序运行测试,但它必须具有某种机制来“获取”下一个方法(随机)来运行它。我正在考虑覆盖它并在那里添加 EM.clear() 。
    • 然后您可以实现 TestListener - 请参阅答案中的更新。
    • 谢谢!这是一个好的开始。我会看看我可以从哪里开始以及可能出现的任何问题。
    • 或者,您可能想要使用类似于本文中描述的技术:beust.com/weblog/2010/03/23/better-mock-testing-with-testng
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多