有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java testNG优先级和依赖性

我对优先事项有一些问题&;依赖于testNG。例如,如果我有这个

@Test
public void login () { ... }

@Test (dependsOnMethods = {"login"})
public void method1 () { ... }

@Test (dependsOnMethods = {"method1"})
public void method2 () { ... }

@Test (dependsOnMethods = {"login"})
public void logout () { ... }

在这种情况下,它的运行方式如下:

登录-->;方法1-->;注销-->;方法2

既然我不再有联系,这就行不通了

你会对我说,注销取决于方法2,一切都会正常

是的,它会。。。但当method1或Method2失败时,它将跳过注销,而不是进行注销。。。这不是我想要的

然后你会说我。。。在这种情况下,只需使用优先级而不是依赖项就很容易了。。。。是的但是如果method1失败了怎么办。。。那么方法2可能是好的,但由于方法1失败,所以无法工作,所以我会有一个假阴性

你知道怎么做吗


共 (3) 个答案

  1. # 1 楼答案

    我相信,当这个问题很好地进行头脑风暴时,很少有概念在实施过程中被忽略。希望这能解决这个问题:

    @Test
    public void login () { ... }
    
    @Test (dependsOnMethods = {"login"}, groups = { "afterLogin" })
    public void method1 () { ... }
    
    @Test (dependsOnMethods = {"method1"}, groups = { "afterLogin" }, priority = 1) 
    public void method2 () { ... }
    // you mark dependsOnMethods when it actually "depends on" something prior to its execution and 
    // hence corresponds to the failure of method it is depending on
    
    @Test (dependsOnMethods = {"login"}, priority = 2)
    public void logout () { ... }
    

    这将确保顺序正确 登录-->;方法1-->;方法2-->;注销

    在哪里

    案例1:如果login失败,依赖于它的方法不应该被执行

    案例2:如果方法1或2失败,它不会跳过logout测试

    案例3:如果方法1和2不依赖于登录,那么您实际上可以使用优先级较低/较高/相等的方法执行它们,确保they are all independent

  2. # 2 楼答案

    您可以声明logout依赖于“method2”和always run

    alwaysRun

    public abstract boolean alwaysRun

    If set to true, this test method will always be run even if it depends on a method that failed. This attribute will be ignored if this test doesn't depend on any method or group.

    Default:

    false

    例如:

    @Test
    public void login () { ... }
    
    @Test (dependsOnMethods = {"login"})
    public void method1 () { ... }
    
    @Test (dependsOnMethods = {"method1"})
    public void method2 () { ... }
    
    @Test (dependsOnMethods = {"method2"}, alwaysRun = true)
    public void logout () { ... }
    
  3. # 3 楼答案

    您可以将方法定义为:

            @Test(priority=1)
    public void login()
    {
        System.out.println("login");
    }
    
    @Test(priority=2)
    public void method1()
    {
        System.out.println("Method1");
        Assert.assertEquals("Method1", "login", "invalid msg not verified"); // Here test is failing as the expected value is not matching the actual value
        System.out.println("Verified");
    }
    
    @Test(priority=3)
    public void method2()
    {
        System.out.println("Method2");
        Assert.assertEquals("Method2", "Method2", "invalid msg not verified"); // Method1 fails however method2 is executed as actual and expected value are matching.
        System.out.println("Verified");
    }
    
    @Test(priority=4)
    public void logout()
    {
        System.out.println("logout");
    }
    

    这将帮助您执行优先级为1的所有测试,然后只有它会向优先级为2的测试移动,然后移动到3,然后移动到4。我已经在上面的代码中添加了“Assert”,这将帮助您在任何测试失败的情况下进一步改进