1 package test.parameters; 2 3 import org.testng.TestNG; 4 import org.testng.annotations.BeforeMethod; 5 import org.testng.annotations.Optional; 6 import org.testng.annotations.Parameters; 7 import org.testng.annotations.Test; 8 import org.testng.xml.Parser; 9 10 import java.io.ByteArrayInputStream; 11 12 /** 13 * This class 14 * 15 * @author Cedric Beust, Jul 22, 2004 16 * 17 */ 18 19 public class ParameterSample { 20 21 @Parameters({ "first-name" }) 22 @BeforeMethod beforeTest(String firstName)23 public void beforeTest(String firstName) { 24 // System.out.println("[ParameterSample] Invoked beforeTestMethod with: " + firstName); 25 assert "Cedric".equals(firstName) 26 : "Expected Cedric, got " + firstName; 27 } 28 29 30 @Parameters({ "first-name" }) 31 @Test(groups = { "singleString"}) testSingleString(String firstName)32 public void testSingleString(String firstName) { 33 // System.out.println("[ParameterSample] Invoked testString " + firstName); 34 assert "Cedric".equals(firstName); 35 } 36 37 @Parameters({"this parameter doesn't exist"}) 38 @Test testNonExistentParameter(@ptional String foo)39 public void testNonExistentParameter(@Optional String foo) { 40 41 } 42 main(String[] args)43 public static void main(String[] args) throws Exception { 44 TestNG tng = new TestNG(); 45 String xml = "<suite name=\"dgf\" verbose=\"10\"><parameter name=\"first-name\" value=\"Cedric\" /><test name=\"dgf\"><classes><class name=\"test.parameters.ParameterSample\"></class></classes></test></suite>"; 46 System.out.println(xml); 47 ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes()); 48 tng.setXmlSuites(new Parser(is).parseToList()); 49 tng.run(); 50 } 51 52 } 53