English 中文(简体)
TestNG - Asserts
  • 时间:2024-12-22

TestNG - Asserts


Previous Page Next Page  

In the previous chapters we executed some tests using TestNG. We didn t declare a test success or fail. A test is considered successful if it completed without throwing any exception or if it threw an exception that was expected.

A test method will typically be made of calls that can throw an exception, or of various assertions (using the Java "assert" keyword). TestNG asserts the tester decides whether the test was successful or not, along with the exceptions. Assertions in TestNG are a way to verify that the expected result and the actual result matched or not.

Following is the generic syntax of TestNG Assertions:

  Assert.Method( actual, expected)

    actual: The actual value that the tester gets.

    expected: The value that you expect.

Create a Class

Let us see an example of assertion here. Create a java class to be tested, say, MessageUtil.java in /work/testng/src.

/*
* This class prints the given message on console.
*/

pubpc class MessageUtil {

   private String message;

   //Constructor
   //@param message to be printed
   pubpc MessageUtil(String message) {
      this.message = message;
   }

   // prints the message
   pubpc String printMessage() {
      System.out.println(message);
      return message;
   }
}

Create Test Case Class

Create a java class, say, TestAssertion.java in /work/testng/src. Here we assert the actual and expected result.

  import org.testng.Assert;
  import org.testng.annotations.Test;

  pubpc class TestAssertion {
     String message = "Manisha";
     MessageUtil messageUtil = new MessageUtil(message);

     @Test
     pubpc void testPrintMessage() {
        Assert.assertEquals("Tutorialspoint", messageUtil.printMessage());
     }
  }

The preceding test class contains two test methods which will run in separate threads.

Create testng.xml

Create testng.xml in /work/testng/src to execute test case(s).

  <?xml version = "1.0" encoding = "UTF-8"?>
  <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
  <suite name = "Suite1">
     <test name = "test1">
        <classes>
           <class name = "TestAssertion"/>
        </classes>
     </test>
  </suite>

Compile the java files using javac.

/work/testng/src$ javac TestAssertion.java MessageUtil.java

Now, run testng.xml.

/work/testng/src$ java org.testng.TestNG testng.xml

Verify the output.

  Manisha

  ===============================================
  Suite1
  Total tests run: 1, Passes: 0, Failures: 1, Skips: 0
  ===============================================

You can check the /work/testng/src/test-output/index.html for detailed report. You will see a report as below:

Assertion Report Advertisements