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 } }
@RepeatedTest annotation is used to repeat a test for a specific number of times. The basic syntax of @RepeatedTest is as follows: The annotation @RepeatedTest is used for a test method instead of the annotation @Test. A number is passed as the input parameter of the annotation.
You could put that code in a utility method in a common class, and invoke the common code in both tests. use case: your app/framework supports several databases. so you have one base test class which contains tests for all features and one extension per database which creates the connection, loads the initial DDL/data.
The easiest (as in least amount of new code required) way to do this is to run the test as a parametrized test (annotate with an @RunWith(Parameterized. class) and add a method to provide 10 empty parameters). That way the framework will run the test 10 times.
Yes, You can. Show activity on this post. JUnit Toolbox provides JUnit runners for parallel execution of tests.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With