1.-依赖注入

TestNG支持两种不同类型的依赖项注入:本机(由TestNG本身执行)和外部(由诸如Guice的依赖项注入框架执行)。

1.1-本机依赖项注入

TestNG允许您在方法中声明其他参数。发生这种情况时,TestNG将自动用正确的值填充这些参数。依赖注入可以在以下地方使用:

任何@Before方法或@Test方法都可以声明ITestContext类型的参数。
任何@AfterMethod方法都可以声明ITestResult类型的参数,该参数将反映刚刚运行的测试方法的结果。
任何@Before和@After方法(@BeforeSuite和@AfterSuite除外)都可以声明XmlTest类型的参数,该参数包含当前的<test>标记。
任何@BeforeMethod(和@AfterMethod)都可以声明java.lang.reflect.Method类型的参数 。此参数将接收此@BeforeMethod完成之后(或在为@AfterMethod运行的方法之后)将调用的测试方法。
任何@BeforeMethod都可以声明Object []类型的参数。此参数将接收即将馈入即将到来的测试方法的参数列表,该参数列表可以由TestNG注入,例如java.lang.reflect.Method或来自@DataProvider。
任何@DataProvider都可以声明ITestContext或java.lang.reflect.Method类型的参数 。后一个参数将接收将要调用的测试方法。
您可以使用@NoInjection批注关闭注入:

/**  * @author 北京-宏哥  *   * Java自动化测试框架-09 - TestNG之 依赖注入篇  *  * 2019年11月8日  */public class NoInjectionTest {     @DataProvider(name = "provider")   public Object[][] provide() throws Exception {       return new Object[][] { { CC.class.getMethod("f") } };   }     @Test(dataProvider = "provider")   public void withoutInjection(@NoInjection Method m) {       Assert.assertEquals(m.getName(), "f");   }     @Test(dataProvider = "provider")   public void withInjection(Method m) {       Assert.assertEquals(m.getName(), "withInjection");   } }

下表总结了可以为各种TestNG注释本地注入的参数类型:

Annotation  ITestContext   XmlTest   Method   Object[]   ITestResult 
BeforeSuite Yes No No No No
BeforeTest Yes Yes No No No
BeforeGroups Yes Yes No No No
BeforeClass Yes Yes No No No
BeforeMethod Yes Yes Yes Yes Yes
Test Yes No No No No