对于我正在进行的研究,我需要在运行@AfterMethod的测试方法(@Test)后捕获结果状态(Passed / Failed)。
我一直在使用import org.testng.ITestResult;作为我的研究之一,在进入几个在线博客之后让我的工作更轻松,但似乎它没有成功我的期望,因为总是结果输出通过,即使断言失败
我的代码如下:
public class SampleTestForTestProject {
ITestResult result;
@Test(priority = 1)
public void testcase(){
// intentionally failing the assertion to make the test method fail
boolean actual = true;
boolean expected = false;
Assert.assertEquals(actual, expected);
}
@AfterMethod
public void afterMethod() {
result = Reporter.getCurrentTestResult();
switch (result.getStatus()) {
case ITestResult.SUCCESS:
System.out.println("======PASS=====");
// my expected functionality here when passed
break;
case ITestResult.FAILURE:
System.out.println("======FAIL=====");
// my expected functionality here when passed
break;
case ITestResult.SKIP:
System.out.println("======SKIP BLOCKED=====");
// my expected functionality here when passed
break;
default:
throw new RuntimeException("Invalid status");
}
}
}
控制台中的结果:
[TestNG] Running: C:\Users\USER\AppData\Local\Temp\testng-eclipse--988445809\testng-customsuite.xml
======PASS=====
FAILED: testcaseFail
java.lang.AssertionError: expected [false] but found [true]
我的期望是将测试结果输入变量以通过开关,如上面的代码片段所示,并在测试方法失败时打印“====== FAIL =====”
有人能帮助我抓住每个测试方法(@Test)的执行测试结果。如果我接近的方法是错误的,请帮助我使用正确方法的代码段。
提前谢谢
答案 0 :(得分:10)
就这样做:
public class stacktest {
@Test
public void teststackquestion() {
boolean actual = true;
boolean expected = false;
Assert.assertEquals(actual, expected);
}
@AfterMethod
public void afterMethod(ITestResult result)
{
try
{
if(result.getStatus() == ITestResult.SUCCESS)
{
//Do something here
System.out.println("passed **********");
}
else if(result.getStatus() == ITestResult.FAILURE)
{
//Do something here
System.out.println("Failed ***********");
}
else if(result.getStatus() == ITestResult.SKIP ){
System.out.println("Skiped***********");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
答案 1 :(得分:5)
TestListenerAdapter
为每种情况(成功,跳过,失败)都有方法。我的建议是让你自己的听众这样。
public class MyTestResultListener extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult result) {
// do what you want to do
}
@Override
public void onTestSuccess(ITestResult result) {
// do what you want to do
}
@Override
public void onTestSkipped(ITestResult result) {
// do what you want to do
}
}
然后将您的监听器添加到测试类中。
@Listeners(MyTestResultListener.class)
public class MyTest {
// your tests
}