0

即使afterMethod失败,我也想继续执行测试,有什么解决方案吗?我尝试使用alwaysRun = true,但只有在方法执行之前和之后,测试总是被忽略。

这是一个简单的示例(仅在测试失败时使用断言,想象一些可能失败的逻辑而不是断言),其中 afterMethod 失败并且其余测试被忽略。

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.testng.Assert.assertTrue;

public class Test1 {

    @BeforeMethod
    public void setup() {
        assertTrue(true);
    }

    @Test
    public void test1() {
        System.out.println("firstTest");
    }

    @Test
    public void test2() {
        System.out.println("secondTest");
    }

    @Test
    public void test3() {
        System.out.println("thirdTest");
    }

    @AfterMethod
    public void clearData() {
        assertTrue(false);
    }
}
4

2 回答 2

0

您正在使用硬断言。如果您使用如下 softAssertion :

softAssertion.assertTrue(false);

在代码中:

@BeforeMethod
public void setup() {
    assertTrue(true);
}

@Test
public void test1() {
    System.out.println("firstTest");
}

@Test
public void test2() {
    System.out.println("secondTest");
}

@Test
public void test3() {
    System.out.println("thirdTest");
}

@AfterMethod
public void clearData() {
    SoftAssert softAssertion= new SoftAssert();
    softAssertion.assertTrue(false);
}

你应该得到这个输出:

firstTest
secondTest
thirdTest
PASSED: test2
PASSED: test3
PASSED: test1

===============================================
    Default test
    Tests run: 3, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 3, Passes: 3, Failures: 0, Skips: 0
===============================================

请参阅此处以供参考

此外,如果您hard assertion@Testnot in 中使用configuration annotation,如果出现任何故障,您的测试用例将会运行。

但是您故意使 testng 失败CONFIGURATION,因此当 testng next 中的配置失败或将跳过其他配置时,您可能会看到这种输出。

SKIPPED CONFIGURATION: @BeforeMethod setup
SKIPPED CONFIGURATION: @AfterMethod clearData
SKIPPED CONFIGURATION: @AfterMethod clearData
SKIPPED CONFIGURATION: @BeforeMethod setup
于 2021-10-12T17:21:00.157 回答
0

您可以尝试使用软断言(例如参见https://www.seleniumeasy.com/testng-tutorials/soft-asserts-in-testng-example

于 2021-10-12T13:57:06.000 回答