gpt4 book ai didi

java - 从 java 运行 TestCase 并在 Eclipse JUnit View 上显示结果

转载 作者:太空宇宙 更新时间:2023-11-04 13:59:57 26 4
gpt4 key购买 nike

我定义了一些类,每个类都有几个带有 @Test 注释的公共(public)方法。所有方法都遵循相同的行为模式(从 ID 检索资源、测试是否为空、记录、调用资源上每一行的实际测试)。因此,我在实例化每个方法的抽象类中具体化了这种行为,如下所示:

@Test
public void someTest(){
new BasicTestPattern("X","Y","Z"){ // some parameters to retrieve resources
@Override
protected void testLine(){
someCheck1();
someCheck2();
}
}.run();
}

该解决方案消除了每个测试方法 10-30 行代码。现在,我想进一步使用自定义注释,如下所示:

@TestPattern(param1="X",param2="Y",param3="Z")
public void someTest(){
someCheck1();
someCheck2();
}

最后,我创建了一个小框架来检索带有此新注释的所有方法,以便实例化 BasicTestPattern 并执行它。它在 TestCase 子类中执行得很好,如下所示:

TestCase junit_test = new TestCase(){
@Override
public void runTest() {
pattern.run();
}
};

junit_test.run();

但是,Eclipse 的 JUnit View 中没有显示/列出任何测试。我只看到成功的测试数量。我怎样才能做到这一点 ?谢谢。

最佳答案

您可能需要创建自己的自定义 Runner 来查找用您的 @TestPattern 方法注释的所有方法。 (可能还与 @Test 一起使用?)

然后你的测试类将如下所示:

@RunWith(YourRunner.class)
public class YourTest{

@TestPattern(param1="X",param2="Y",param3="Z")
public void someTest(){
...
}

@Test
public void anotherNormalTest(){
...
}


}

This Blog解释如何编写自定义 Runner。但是您可能可以通过扩展 BlockJUnit4ClassRunner 将您的特殊测试方法添加到要运行的测试列表中。

我认为您只需要重写 computeTestMethods() 方法,这就是 BlockJUnit4ClassRunner 查找所有要运行的测试方法(用 @Test 注释的方法)的方法,您可以重写它来查找用您自己的注释注释的方法。

  public class your TestRunner extends BlockJUnit4ClassRunner{

protected List<FrameworkMethod> computeTestMethods() {
//this is all the @Test annotated methods
List<FrameworkMethod> testAnnotatedMethods = super.computeTestMethods();
//these are all the methods with your @TestPattern annotation
List<FrameworkMethod> yourAnnotatedMethods = getTestClass().getAnnotatedMethods(TestPattern.class);

//do whatever you need to do to generate the test
//methods with the correct parameters based on
//the annotation ?
//Might need to make fake or
//synthetic FrameworkMethod instances?

...

//combine everyting into a single List
List<FrameworkMethod> allTestMethods =...
//finally return all the FrameworkMethods as a single list
return allTestMethods;
}

}

您可能必须创建自己的 FrameworkMethod 实现包装器才能从注释中获取信息,并在调用该方法之前执行所需的任何设置。

这将使其与普通 JUnit 类无缝集成并与 JUnit IDE View 一起使用

祝你好运

关于java - 从 java 运行 TestCase 并在 Eclipse JUnit View 上显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29392443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com