In Java test automation using TestNG, two commonly used methods for verification are Assert and Verify. Both methods are used to verify whether a condition is true or false. However, there are some differences between the two that are important to understand.
Assert:
The Assert method is used to verify that a condition is true. If the condition is false, the Assert method will throw an AssertionError and the test case will fail. Here's an example of using Assert:
@Test
public void testAddition() {
int a = 2;
int b = 3;
int result = a + b;
Assert.assertEquals(result, 5);
}
In this example, the Assert.assertEquals() method verifies that the result of adding a and b is equal to 5. If the result is not equal to 5, the test case will fail with an AssertionError.
Verify:
The Verify method is also used to verify that a condition is true, but it doesn't throw an exception if the condition is false. Instead, it logs the failure and continues to execute the test case. Here's an example of using Verify:
@Test
public void testAddition() {
int a = 2;
int b = 3;
int result = a + b;
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(result, 5);
softAssert.assertAll();
}
In this example, the SoftAssert class is used to perform the verification. The SoftAssert.assertEquals() method verifies that the result of adding a and b is equal to 5. However, the test case will continue to execute even if the condition is false. The softAssert.assertAll() method is called at the end of the test case to verify that all assertions have passed. If any assertion has failed, the test case will fail.
The main differences between Assert and Verify are:
Assert throws an exception and stops the test case when the condition is false, while Verify logs the failure and continues to execute the test case.Assert is typically used for critical checks that should stop the test case when they fail, while Verify is used for non-critical checks that should log the failure but allow the test case to continue.
In general, it's a good practice to use Assert for critical checks and Verify for non-critical checks. However, the choice between the two methods ultimately depends on the requirements of the specific test case.
Difference between Assert and Verify in test automation using TestNG