Java 对JUnit和Cucumber使用相同的类加载器
我有一个cucumber测试,它使用Java 对JUnit和Cucumber使用相同的类加载器,java,groovy,junit,cucumber,Java,Groovy,Junit,Cucumber,我有一个cucumber测试,它使用@RunWith(cucumber)运行。该测试使用来自其他类的静态字段。它看起来像: 黄瓜试验 @RunWith(Cucumber) @CucumberOptions( features = 'src/test/resources/features/cucumber-test.feature', glue = ['src/test/groovy'] ) class CucumberTest { @BeforeClass static void
@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
}
cumber 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.field
行,静态块只执行一次。这一次只使用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使用相同的类加载器?看看您的
Cucumber选项
:
glue = ['src/test/groovy']
此语句导致生成一个单独的Groovy类装入器,以直接从指定的源文件夹获取类(并重新编译它们)
您只需指示Cucumber从类路径中获取Groovy步骤定义即可
glue = ['classpath:your.step.definitions.package.name']
或者更简单一些:
glue = ['classpath:']
-如果你根本不想关心包名。但请注意,在许多情况下,最后一个可能是不可接受的,因为它将触发对所有可用类路径的扫描/加载,因此对于步骤定义,坚持使用精确的包名通常是首选的