JUnit测试互相影响 [英] JUnit tests influence each other

查看:107
本文介绍了JUnit测试互相影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理大量遗留代码。有一个JUnit-TestSuite开始。使用gradle运行所有测试时,失败。在IntelliJ中运行测试时,他们工作。我们配置了gradle以使用测试套件。

现在有人报告了在本地没有gradle的测试,但没有使用gradle。现在是我们解决这个混乱的时候了。

是否有一种明智的方法来确定哪个测试会在后面留下一些配置,或者哪些测试依赖于其他测试?

解决方案

从一次测试到另一次测试的流血最可能的原因是可变静态值。默认情况下,所有测试都由同一个JVM运行,因此一个测试变异的静态变量将在另一个测试中变得脏。



可变静态邪恶!我正在研究一个目前各地都有可变静态代码的代码库,这是一团糟。如果可能的话,你应该重构使用依赖注入并在实例中存储可变状态,而不是静态。



作为一种解决方法,为了让gradle中运行的测试可以使用 Test.forkEvery 为每个测试使用一个单独的JVM,因此每个测试调用的静态变量都将是干净的。例如

  test {
forkEvery = 1
}


I'm working with a lot of legacy code. There was a JUnit-TestSuite to begin with. When running all tests with gradle, they failed. When running the test in IntelliJ, they worked. We configured gradle to use the test suite.

Now someone reported tests working locally without gradle, but not with gradle. It's time we fix this mess.

Is there a smart way to figure out which test leaves some configuration behind or which tests relies on the other tests?

解决方案

The most likely cause of this "bleed" from one test into another is mutable static values. By default, all tests are run by the same JVM so a static variable which is "mutated" by one test will be "dirty" in another test.

Mutable statics are evil! I'm working on a codebase currently with mutable statics everywhere and it's a mess. If possible you should refactor to use dependency injection and store mutable state in instances and not statics.

As a workaround, to get the tests running in gradle you could use Test.forkEvery to use a separate JVM per test so static variables will be "clean" for each test invocation. Eg

test {
    forkEvery = 1
}

这篇关于JUnit测试互相影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆