【问题标题】:Use same classloader for JUnit and Cucumber对 JUnit 和 Cucumber 使用相同的类加载器
【发布时间】:2023-04-07 03:17:01
【问题描述】:

我有一个使用@RunWith(Cucumber) 运行的黄瓜测试。该测试使用来自其他类的静态字段。它看起来像:

黄瓜测试

@RunWith(Cucumber)
@CucumberOptions(
  features = 'src/test/resources/features/cucumber-test.feature',
  glue = ['src/test/groovy']
)
class CucumberTest {
  @BeforeClass
  static void setUp() {
    StaticClass.filed
  }
}

静态类

class StaticClass {
  static {
    filed = UUID.randomUUID().toString()
    println "Field initialized with value $filed in ${this.classLoader.toString()}\n"
  }
  static String filed
}

cucumber-test.feature 仅包含行 Feature: None,并且没有步骤定义。当我运行这个测试时,输出是

Field initialized with value 649b6d18-fe5a-4993-a92e-74645c3ab07d in groovy.lang.GroovyClassLoader$InnerLoader@534a5a98
Field initialized with value 9639e4de-661f-4ac7-afc9-715cdd17bb35 in sun.misc.Launcher$AppClassLoader@4e25154f

所以静态块被执行了两次,但是使用了不同的类加载器。看起来有一个用于 JUnit 的类加载器,另一个用于 Cucumber runner。

另外,如果我在setUp 方法中注释掉StaticClass.filed 行,静态块只会执行一次。这次只使用 Groovy 类加载器

Field initialized with value 73d1d302-826c-4ec3-a9db-c065b399487f in groovy.lang.GroovyClassLoader$InnerLoader@5a45133e

我的项目中的依赖项是:

dependencies {
  compile 'info.cukes:cucumber-groovy:1.2.5'
  compile 'info.cukes:cucumber-junit:1.2.5'
  compile 'org.codehaus.groovy:groovy-all:2.4.12'
}

有没有办法为 JUnit 和 Cucumber runner 使用相同的类加载器?

【问题讨论】:

    标签: java groovy junit cucumber


    【解决方案1】:

    看看你的CucumberOptions

    glue = ['src/test/groovy']
    

    该语句导致生成一个单独的 Groovy 类加载器,以直接从指定的源文件夹获取类(并因此重新编译它们)

    您只需要指示 Cucumber 从类路径中获取 Groovy 步骤定义

    glue = ['classpath:your.step.definitions.package.name']
    

    甚至更简单:

    glue = ['classpath:'] 
    

    - 如果您根本不想关心包名称。但请注意,在许多情况下,最后一个可能不可接受,因为它会触发对所有可用类路径的扫描/加载,因此通常首选使用精确的包名称进行步骤定义

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多