如何调用方法而不重复java中的其他方法 [英] How to call a method without repeat from other methods in java

查看:151
本文介绍了如何调用方法而不重复java中的其他方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有成千上万的方法,如:

For example, I have thousands of method like:

AA() {
    ...
}  
BB() {
    ...
}  
CC() {
    ...
}  
etc ...

现在我想在每个方法的开头调用一个方法printCurrentMethodName()。这意味着,

Now I want to call a method printCurrentMethodName() on the beginning of each method. That means,

AA() {
    printCurrentMethodName();
    ...
}  
BB() {
    printCurrentMethodName();
    ...
}  
CC() {
    printCurrentMethodName();
    ...
}  
etc ...

包括printCurrentMethodName()在数以千计的方法开始是耗时的。

Including printCurrentMethodName() on the start of thousands of method is time consuming.

有没有什么方法可以在每个方法的开头调用printCurrentMethodName()而不用重复数千个方法?

Is there any way that I can call printCurrentMethodName() on the beginning of each methods without repeating it in those thousands of method?

(我不能使用@Before或@BeforeMethod注释之类的东西,因为它会在输入AA()之前调用printCurrentMethodName(),因此它不会打印方法名称如预期的那样)

(I can't use something like @Before or @BeforeMethod annotation, because it will call printCurrentMethodName() before entering AA() and so it will not print the method name as expected)

推荐答案

如果您只想打印测试方法的名称,那么您可以创建一个 JUnit规则类似于 TestName规则

If you only want to print the names of the test methods then you could create a JUnit rule that is similar to the TestName rule

public class PrintTestName extends TestWatcher {
  @Override
  protected void starting(Description d) {
      System.out.println(d.getMethodName());
  }
}

并在测试中使用

public class YourTest {
  @Rule
  public final PrintTestName printTestName = new PrintTestName();

  @Test
  public AA() {
    ...
  }

  ...

这篇关于如何调用方法而不重复java中的其他方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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