Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

java - How to reuse existing JUnit tests in another test class?

how can I reuse JUnit tests in another testclass?

For example:

public TestClass1 {
    @Test
    public void testSomething(){...}
}

public TestClass2 {
    @Test
    public void testSomethingAndSomethingElse() {
        // Somehow execute testSomething()
        // and then test something else
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Avoid the scenario, in general. It is prone to making tests much more brittle. If TestClass1 fails, then TestClass2 implicitly fails, which isn't desirable for at least the following reasons:

  • Code is tested more than once, which wastes execution time.
  • Tests should not rely on each other, they should be as decoupled as possible
  • If this becomes a pattern, it will become harder to identify what section of code is broken by looking at which tests are failing, which is part of the point of tests

Occasionally sharing sections of test code is useful, particularly for integration tests. Here's how you might do it without depending on the tests themselves:

public abstract BaseTests {

    protected void somethingHelper() {
        // Test something
    }
}

public TestClass1 extends BaseTests {
    @Test
    public void testSomething(){
        somethingHelper();
    }
}

public TestClass2 extends BaseTests {
    @Test
    public void testSomethingAndSomethingElse() {
        somethingHelper();
        // and then test something else
    }
}

Alternatively, you could use a helper class and avoid the inheritance altogether. Asserts and the like can go in the somethingHelper() method.

Don't call a method from TestClass1 in TestClass2 directly. The test cases become less readable this way, and can lead to spaghetti frittata.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...