开发者

How to deal with interdependent JUnit tests?

开发者 https://www.devze.com 2023-03-19 18:50 出处:网络
I have a question about JUnit testing. Our JUnit suite is testing various functions that we wrote that interact with our memory system.

I have a question about JUnit testing.

Our JUnit suite is testing various functions that we wrote that interact with our memory system.

The way our system was designed, requires it to be static, and therefore initialized prior to the running of the tests.

The problem we are having is that when subsequent tests are run, they are affected by tests prior to it, so it is possible (and likely) that we are getting false positive, or innaccurate failures.

Is there a way to maintain the testing order of our JUnit tests, but have it re-initialize the entire system, as if testing on the system from scratch.

The only option we can think of is to write a method that does this, and call it at the end of each test, but as there are lots and lots of things that need to be reset this way, I am hoping there is a simpler way to do this.开发者_如何学Go


I've seen problems with tests many times where they depend on each other (sometimes deliberately!).

Firstly you need to setup a setUp method:

@Before
public void setUp() {
    super.setUp();
    // Now clear, reset, etc all your static data.
}

This is automatically run by JUnit before each test and will reset the environment. You can add one after as well, but before is better for ensuring a clean starting point.

The order of your tests is usually the order they are in the test class. But this should never be assumed and it's a really bad idea to base code on that.

Go back to the documentation. If you need more information.


The approach I took to this kind of problem was to do partial reinitialization before each test. Each test knows the preconditions that it requires, and the setup ensures that they are true. Not sure if this will be relevant for you. Relying on order often ends up being a continuing PITA - being able to run tests by themselves is better.

Oh yeah - there's one "test" that's run as the beginning of a suite that's responsible for static initialization.


You might want to look at TestNG, which supports test dependencies for this kind of functional testing (JUnit is a unit testing framework):

@Test
public void f1() {}

@Test(dependsOnMethods = "f1")
public void f2() {}
0

精彩评论

暂无评论...
验证码 换一张
取 消