How to reuse existing JUnit tests in another test class?

后端 未结 4 1128
广开言路
广开言路 2020-12-16 09:29

how can I reuse JUnit tests in another testclass?

For example:

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

public TestClass         


        
4条回答
  •  有刺的猬
    2020-12-16 10:15

    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.

提交回复
热议问题