在TestNG中使用@BeforeMethod时,有没有办法获取方法元数据? [英] Is there a way to get method meta data when using @BeforeMethod in TestNG?

查看:27
本文介绍了在TestNG中使用@BeforeMethod时,有没有办法获取方法元数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 TestNG 并有一套测试.我想在每个需要有关方法信息的测试方法之前执行一个操作.作为一个简单的例子,假设我想在执行之前打印方法的名称.我可以编写一个用 @BeforeMethod 注释的方法.如何将参数注入该方法?

I am using TestNG and have a suite of tests. I want to perform an action before every test method that requires information about the method. As a simple example, say I want to print the name of the method before its executed. I can write a method annotated with @BeforeMethod. How can I inject parameters into that method?

推荐答案

查看依赖注入 部分.它指出在这种情况下可以使用依赖注入:

Take a look at the dependency injection section in the documentation. It states that dependency injection can be used for example in this case:

任何@BeforeMethod(和@AfterMethod)都可以声明一个java.lang.reflect.Method 类型的参数.此参数将接收将在此 @BeforeMethod 完成后(或在为 @AfterMethod 运行的方法之后)调用的测试方法.

Any @BeforeMethod (and @AfterMethod) can declare a parameter of type java.lang.reflect.Method. This parameter will receive the test method that will be called once this @BeforeMethod finishes (or after the method as run for @AfterMethod).

所以基本上你只需要在你的 @BeforeMethod 中声明一个 java.lang.reflect.Method 类型的参数,你就可以访问以下名称测试名称.类似的东西:

So basically you just have to declare a parameter of type java.lang.reflect.Method in your @BeforeMethod and you will have access to the name of the following test name. Something like:

@BeforeMethod
protected void startTest(Method method) throws Exception {
    String testName = method.getName(); 
    System.out.println("Executing test: " + testName);
}

还有一种方法是使用 ITestNGMethod 接口(documentation),但由于我不确定如何使用它,如果您有兴趣,我会让您看看它.

There's also a way by using the ITestNGMethod interface (documentation), but as I'm not exactly sure on how to use it, I'll just let you have a look at it if you're interested.

这篇关于在TestNG中使用@BeforeMethod时,有没有办法获取方法元数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆