如何解决间歇性 junit 测试失败问题?

发布于 2024-12-09 10:03:58 字数 471 浏览 0 评论 0原文

我正在处理一个案例,我的测试根据声明的顺序通过或失败。这当然表明没有正确隔离测试。但我对如何找到问题感到困惑。 问题是我的 junit 测试派生自一个类,该类属于基于 junit 构建的测试框架,并且具有一些依赖项注入容器。基类设置会为每次测试重置容器,因此至少在容器中没有延迟对象,因为容器本身是新的。所以我倾向于以下场景。

  1. test1 间接导致某个 classA 将 classA.somestaticMember 设置为 xyz 值。 test obj 不直接维护对 classA 的任何引用 - 但当 test1 结束时, vm 仍会加载 classA ,其值为 xyz 。
  2. test2 访问 classA 并在某个具有 xyz 值的静态成员上出错。

问题是 a) 我不知道情况是否确实如此——我该如何找到它?我似乎无法在代码中找到对静态变量的引用...... b) 有没有办法告诉 junit 转储所有加载的类并为每个测试方法重新执行?

I am dealing with a case where my tests pass or fail based on the order of declaration. This of-course points to not properly isolated tests. But I am stumped about how to go about finding the issue.
The thing is my junit tests derive from a class that is belongs to a testing framework built on junit and has some dependency injection container. The container gets reset for every test by the base class setup and so there are no lingering objects at least in the container since the container itself is new. So I am leaning toward the following scenario.

  1. test1 indirectly causes some classA which sets up classA.somestaticMember to xyz value. test obj does not maintain any references to classA directly- but classA is still loaded by vm with a value xyz when test1 ends.
  2. test2 access classA and trips up on somestaticmember having xyz value.

The problem is a) I dont know if this is indeed the case- how do I go about finding that ? I cannot seem to find a reference to a static var in the code...
b) is there a way to tell junit to dump all its loaded classes and do it afresh for every test method ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那一片橙海, 2024-12-16 10:03:58

您可以使用 @Before 声明一个方法,

@Before public void init()
{
    // set up stuff
}

JUnit 将在每次测试之前运行它。您可以使用它来设置“夹具”(一组已知的新对象、数据等,您的测试将彼此独立地使用它们)。

还有一个@After,您可以使用它来执行每次测试之后所需的任何清理工作。您通常不需要这样做,因为 Java 会清理您使用的任何对象,但它对于将外部对象(您不创建和控制的东西)恢复到已知状态可能很有用。

(但请注意:如果您依赖外部对象来进行测试,那么您所拥有的就不再是单元测试。您不能真正说出失败是由于您的代码还是外部对象造成的,这就是单元测试的目的之一。)

You can declare a method with @Before, like

@Before public void init()
{
    // set up stuff
}

and JUnit will run it before each test. You can use that to set up a "fixture" (a known set of fresh objects, data, etc that your tests will work with independently of each other).

There's also an @After, that you can use to do any cleanup required after each test. You don't normally need to do this, as Java will clean up any objects you used, but it could be useful for restoring outside objects (stuff you don't create and control) to a known state.

(Note, though: if you're relying on outside objects in order to do your tests, what you have isn't a unit test anymore. You can't really say whether a failure is due to your code or the outside object, and that's one of the purposes of unit tests.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文