您能否以编程方式调用方法,就好像它是类字段一样

本文关键字:字段 一样 编程 方式 调用 方法 | 更新日期: 2023-09-27 18:19:11

我正在为我的程序编写一个自动化测试套件,并且一直在寻找简化和重构大量代码的方法。

目前,我有许多 try/catch 块(因为我希望能够从一个测试移动到下一个测试,即使在失败的情况下也是如此(,否则可以记录信息。它看起来有点像这样:

try
{
    PerformTest1();
}
catch(Exception e)
{
    file.WriteLine("Unable to perform test number 1.");
    file.WriteLine("Error: " + e.Message);
    file.WriteLine("StackTrace: " + e.StackTrace);
}
try
{
    PerformTest2();
}
catch(Exception e)
{
    file.WriteLine("Unable to perform test number 2.");
    file.WriteLine("Error: " + e.Message);
    file.WriteLine("StackTrace: " + e.StackTrace);
}

等等。我想知道我是否可以制作这些测试的数组,以便我可以使用循环。像这样:

foreach(Test t in testsArray)
{
    try
    {
        t.RunTest();
    }
    catch(Exception e)
    {
        file.WriteLine(t.failDescription);
        file.WriteLine("Error: " + e.Message);
        file.WriteLine("StackTrace: " + e.StackTrace);
    }
}

我如何执行此操作,但不使每个测试都是自己的类(使用 RunTest(( 方法(?我正在考虑制作一个测试类,其中包含必要的字段,其中一个是方法。然后,我可以创建一个测试对象,并调用该对象方法。这样的事情可能吗?还是我必须进行多个测试类?

您能否以编程方式调用方法,就好像它是类字段一样

您需要

一个带有runTest()方法的Test接口,但是您可以使用匿名类或lambda表达式(如果您使用的是Java 8(来实现逻辑,这将节省为每个测试创建显式类的需要。

例:

Test test1 = new Test () {
    public void runTest () {
    // logic of first test here
    }
};

实际上,您不需要创建自己的界面。使用现有的Runnable接口及其run()方法。

Runnable test1 = new Runnable () {
    public void run () {
    // logic of first test here
    }
};

或使用 lambda 表达式:

Runnable test1 = () -> {
                        // logic of first test here
                       };

然后,您可以将这些Runnable中的每一个添加到列表(或数组(中,并根据需要循环运行它们:

for (Runnable test in testsArray)
{
    try {
       test.run();
    }
    catch(Exception e)
    {
       ...
    }
} 

您可以使用一些 Lambda 技巧:

var actions = new List<Action>();
actions.Add(PerformTest1);  // requires a void PerformTest1() method
actions.Add(PerformTest2);
//...  and so on...

然后最后触发所有操作:

foreach(var action in actions)
{
   action();
}

您是否研究过 .Net/Java 的可用测试框架?我相信Nunit(或JUnit(提供了您正在寻找的许多功能,包括在发生故障时写出堆栈跟踪和异常详细信息。

它还将多个测试封装在一个测试夹具中,因此允许您在失败后仍执行后续测试,而不会在各个测试之间泄露数据或状态。

public interface Testable {
    void doTest();
}
public class Test1 implements Testable {
    // implement doTest()
}
private static Testable[] testables = new Testabable[] {
    new Test1()
};
// now iterate your testables and call doTest()

好吧,似乎是老派的,但这是第一件事,应该学习接口。