访问另一个类中的内部枚举进行测试 [英] Accessing inner enum in another class for testing

查看:727
本文介绍了访问另一个类中的内部枚举进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问另一个类中的内部枚举类?例如:

How do I access inner enum classes in another class? For example:

public class Foo {
    enum Bar {
        ONE, TWO, FOUR, EIGHT, SIXTEEN
    }

    // ...methods here
}

我试图访问 Foo.Bar 的类:

public class FooTest {
    private Foo f;

    @Before
    public void setUp() throws Exception {
        f = new Foo();
    }

    public void testCase1() {
        assertEquals(Bar.ONE, f.climbUp());
    }
}

我尝试过 Foo .Bar.ONE Bar.ONE 以及使用 Foo.class.getDeclaredField(Bar )但这些似乎都没有工作。 getDeclaredClasses()似乎让我 $ Bar ,但是我无法访问任何东西。

I've tried Foo.Bar.ONE, Bar.ONE as well as making a new variable using Foo.class.getDeclaredField("Bar") but none of these seem to be working. getDeclaredClasses() seems to get me $Bar but I can't access anything from there.

更新:我不允许修改课程 Foo

推荐答案

如果目标是测试它,但是将枚举保持在默认的可访问性( package-private ),这是您无法编辑 Foo 和其他类的标题所隐含的,那么通常的方法是在同一个包中进行测试。意思是可以使用 default 可见性(见这里)。

If the goal is to test it, but keep the enum in the default accessibility (package-private), which is implied by your inability to edit Foo and the title of the other class, then a common approach is to make the test in the same package. Meaning it can access the items with default visibility (see here).

测试:

package com.scratch;

public class FooTest {
    public static void main(String[] args) {
        System.out.println(String.valueOf(Foo.Bar.ONE));
    }
}

另一个来源:

package com.scratch;

public class Foo {
    enum Bar {
        ONE, TWO;
    }
}

这篇关于访问另一个类中的内部枚举进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆