英文:
Junit categories - which category I am in?
问题
我正在使用JUNIT的@categories,并且想要在一个方法中检查我属于哪个分类。
例如:
如果(category.name ==“sanity”)
//执行某些操作
有没有办法做到这一点?
我希望避免在此方法中传递参数,因为在项目中有800多个对它的调用
英文:
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
答案1
得分: 1
以下是翻译好的部分:
我相信你可以以与确定任何其他类是否具有特定注释及其值的方式相同的方式来完成这个操作 - 使用Java的反射机制。
以你的特定情况为例,你可以这样做:
@Category(Sanity.class)
public class MyTest {
@Test
public void testWhatever() {
if (isOfCategory(Sanity.class)) {
// 针对属于Sanity类别的任何测试所需的特定操作:
System.out.println("运行Sanity测试");
}
// 进行任何你需要的测试...
}
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;
}
}
英文:
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论