Junit分类 – 我属于哪个类别?

huangapple go评论74阅读模式
英文:

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(&quot;Running Sanity Test&quot;);
        }
        // test whatever you need...
    }

    private boolean isOfCategory(Class&lt;?&gt; categoryClass) {
        Class&lt;? extends MyTest&gt; thisClass = getClass();
        if (thisClass.isAnnotationPresent(Category.class)) {
            Category category = thisClass.getAnnotation(Category.class);
            List&lt;Class&lt;?&gt;&gt; values = Arrays.asList(category.value());
            return values.contains(categoryClass);
        }
        return false;
    }
}

huangapple
  • 本文由 发表于 2020年7月26日 16:20:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63097770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定