Java Selenium WebDriver code to implement Verify instead of Assert

前端 未结 3 1097
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 14:03

I am not able to understand how to write Java code to implement Verify. I am always seeing the code to implement Assert but not for Verify

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-21 14:30

    TestNG does not support verify statements, but they can be implemented easily. The simplest way is to use Java StringBuffer in your test method like below,

    @Test
    public void verifyTest(){  
    
        /* buffer to hold your errors */
        StringBuffer errorBuffer = new StringBuffer();      
    
        /* verification 1 */
        try{        
            Assert.assertEquals("value1", "value!");            
        }catch(AssertionError e){           
            errorBuffer.append(e.getMessage() + "\n");      
        }       
    
        /* verification 2 */
        try{            
            Assert.assertEquals("value2", "value!");            
        }catch(AssertionError e){           
            errorBuffer.append(e.getMessage());     
        }
    
        if(errorBuffer.length() > 0){
            throw new AssertionError(errorBuffer.toString()); 
        }
    
    }
    

    For more advanced implementation you can use TestNG's IInvokedMethodListener interface where you need to implement two methods from that interface,

    public class TestMethodListener implements IInvokedMethodListener{
    
        @Override
        public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
    
            if(method.isTestMethod()){              
                /* create new error buffer object */                
            }
    
        }
    
        @Override
        public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
    
            if(method.isTestMethod()){              
                /* process your test result for verification errors stored in error buffer
                 * and modify your testResult object accordingly
                 */                 
            }
    
        }
    
    }
    

    Most of the time we don't have to go for advanced implementation. Simple StringBuffer should work. But if you want to use verify statements frequently in your test then implementing IInvokedMethodListener would be reasonable. If you are interested in advanced implementation then please check this blog https://muthutechno.wordpress.com/2015/01/26/implementing-verify-statements-for-testng-framework/

提交回复
热议问题