【问题标题】:Need help For building Testing Framework需要帮助构建测试框架
【发布时间】:2013-10-15 13:41:02
【问题描述】:

最近我试图构建一个像 TestNG 这样的框架,但遇到了 Launcher 的问题(我不知道是 Launcher 的问题还是其他只是猜测的问题)。所以这就是我所做的。

  1. 首先我创建了一个名为 Test 的自定义注解
  2. 用main方法写了一个测试注解的实现类(现在我只针对一个注解)
  3. 在实现类的主要方法中,我编写了读取 xml 的代码(这样我就可以获取类名并使用反射,我正在使用 Test 注释检查类的方法并调用它)。
  4. 现在我用带有测试注释的方法编写了另一个类,并在 xml 文件中提到了类名。现在,当我们使用testng 时,我们可以选择将该方法/类作为TestNG 运行。
  5. 但就我而言,我不知道如何运行我的 Class,因为没有 main 方法。
  6. 所以我在这一点上感到震惊。请建议我应该做什么。如果我们需要 Launcher,请告诉我们如何创建启动器或任何教程/书籍/网络链接,其中包含有关 Launcher 的信息。

*注意:我知道如果我们使用注解,我们就不需要 XML 文件。但是为了简化事情,我稍后会从 XML 中获取类名,我将丢弃 XML。

提前致谢。

这是我的测试注释

包com.annoatation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value=ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {

}

这是我使用 Annotation 的课程:

package com.annoatation;

public class TestExample{
    @Test
    public void sampleMethod()
     {
        System.out.println("This is sample method");
    }
    @Test
    public void sampleMethod1()
    {
            System.out.println("This is sample method 1");
    }

}

这是我的主要课程:

package com.annoatation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) {
        TestExample example=new TestExample();
        Method[] method=example.getClass().getMethods();
        for(Method methods:method)
        {
            Test test=methods.getAnnotation(com.annoatation.Test.class);
            if(test!=null)
            {
                try {
                    methods.invoke(example);
                } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
       }

    }

}

我希望当我单击我的 TestExample 类上的运行方式时,它应该自动调用主类的主要方法。 我不确定我们在 java 中说什么(可能是入口点)

【问题讨论】:

    标签: java testing groovy frameworks


    【解决方案1】:

    使用反射创建类的实例并调用带注释的方法:

    Class classDefinition = Class.forName(className);
    object = classDefinition.newInstance();
    
    Method method = classDefinition.getMethod("methodName");
    method.invoke(object);
    

    【讨论】:

      猜你喜欢
      • 2013-02-24
      • 2019-12-16
      • 1970-01-01
      • 2011-12-19
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      相关资源
      最近更新 更多