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
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/