Issue
I am using JUNIT's @categories and want to check in a method which category I am in.
for example if (category.name == "sanity") //do something
Is there any way to do that? I want to avoid having to pass a parameter to this method because I have over 800 calls to it in the project
Solution
I believe you can do that the same way that can be used to determine if any other class has specific annotation and its values - use Java reflection mechanism.
As a quick example for your specific case you can make it like this:
@Category(Sanity.class)
public class MyTest {
@Test
public void testWhatever() {
if (isOfCategory(Sanity.class)) {
// specific actions needed for any tests that falls into Sanity category:
System.out.println("Running Sanity Test");
}
// test whatever you need...
}
private boolean isOfCategory(Class<?> categoryClass) {
Class<? extends MyTest> thisClass = getClass();
if (thisClass.isAnnotationPresent(Category.class)) {
Category category = thisClass.getAnnotation(Category.class);
List<Class<?>> values = Arrays.asList(category.value());
return values.contains(categoryClass);
}
return false;
}
}
Answered By - Alexei Kovalev