Adam Lee
Adam Lee

Reputation: 25738

Any annotation to mark a class as a testclass?

I am new to Junit4, I am wondering if there is some annotations to mark a class as a test class just like using

@Test to mark a method as a test method.

Upvotes: 2

Views: 2798

Answers (2)

Matthew Mitchell
Matthew Mitchell

Reputation: 514

Annotation @TestOnly, but it does come with a warning, as seen below.

import org.jetbrains.annotations.TestOnly;

WARNING

/**
 * A member or type annotated with TestOnly claims that it should be used from testing code only.
 * <p>
 * Apart from documentation purposes this annotation is intended to be used by static analysis tools
 * to validate against element contract violations.
 * <p>
 * This annotation means that the annotated element exposes internal data and breaks encapsulation 
 * of the containing class; the annotation won't prevent its use from production code, developers 
 * won't even see warnings if their IDE doesn't support the annotation. It's better to provide 
 * proper API which can be used in production as well as in tests.
 */

WORKAROUND

If there are bodies of code or classes that I use specifically for testing and need to remove them at release I add a custom TODO using Android Studio (Not sure if other IDEs have the same functionality), follow the screenshot below and in the TODO tab at the bottom, you will see a filter for each custom TODO on the left. This is by no means the best way to do it, but I find it the fastest manual way to remove code on release.

Custom TODO in Android Studio

TODO Filter

P.S I know the patterns are all sorts of messed up in this screenshot.

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 30985

You can use @Category annotation at class level, like:

@Category({PerformanceTests.class, RegressionTests.class})
public class ClassB {

    @Test
    public void test_b_1() {
        assertThat(1 == 1, is(true));
    }

}

I quoted this example from https://www.mkyong.com/unittest/junit-categories-test/

Also if you run Spring tests, Mockito test with JUnit, then you have to use @RunWith annotation at class level.

For example in Spring boot test I use this:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class ControllerTest {

In Mockito (without spring test) test I used:

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

Upvotes: 1

Related Questions