Java – how to group / classify a large number of JUnit tests
In our project, we currently have a large number of JUnit tests, which are divided into three categories: unit, integration and ticket gate
I now want to group these tests so that I can only run one (or both) of them The only thing I found was the JUnit test suite and categories, as follows: http://www.wakaleo.com/component/content/article/267
My problem is that I don't want to declare every test in test suits with @ suitecalasses
Is there any way to add a suite class with wildcards / patterns?
Solution
Assuming my understanding of this problem is correct, I can actually use JUnit to complete it The following code is used with JUnit 4.11 and allows us to divide all tests into two categories: "unclassified" and integration
IntegrationTestSuite. java
/** * A custom JUnit runner that executes all tests from the classpath that * match the <code>ca.vtesc.portfolio.*Test</code> pattern * and marked with <code>@Category(IntegrationTestCategory.class)</code> * annotation. */ @RunWith(Categories.class) @IncludeCategory(IntegrationTestCategory.class) @Suite.SuiteClasses( { IntegrationTests.class }) public class IntegrationTestSuite { } @RunWith(ClasspathSuite.class) @ClasspathSuite.ClassnameFilters({ "ca.vtesc.portfolio.*Test" }) class IntegrationTests { }
UnitTestSuite. java
/** * A custom JUnit runner that executes all tests from the classpath that match * <code>ca.vtesc.portfolio.*Test</code> pattern. * <p> * Classes and methods that are annotated with the * <code>@Category(IntegrationTestCategory.class)</code> category are * <strong>excluded</strong>. */ @RunWith(Categories.class) @ExcludeCategory(IntegrationTestCategory.class) @Suite.SuiteClasses( { UnitTests.class }) public class UnitTestSuite { } @RunWith(ClasspathSuite.class) @ClasspathSuite.ClassnameFilters({ "ca.vtesc.portfolio.*Test" }) class UnitTests { }
IntegrationTestCategory. java
/** * A marker interface for running integration tests. */ public interface IntegrationTestCategory { }
The first sample test below is not annotated with any categories, so all its test methods will be included when running unittestsuite and excluded when running integration TestSuite
public class OptionsServiceImpltest { @Test public void testOptionAssignment() { // actual test code } }
The next example is marked as an integration test at the class level, which means that its test methods will be excluded when running unittestsuite and including it in the integration TestSuite:
@Category(IntegrationTestCategory.class) public class PortfolioServiceImpltest { @Test public void testTransfer() { // actual test code } @Test public void testQuote() { } }
The third example demonstrates a test class in which one method has no comments and the other is marked as an integration class
public class MarginServiceImpltest { @Test public void testPayment() { } @Test @Category(IntegrationTestCategory.class) public void testCall() { } }