如何使用JUNIT测试ENUM?

12

我该如何使用JUNIT创建测试用例以测试ENUM类型。下面是我添加了枚举类型的代码。

public class TrafficProfileExtension {
public static enum CosProfileType {
    BENIGN ("BENIGN"), 
    CUSTOMER ("CUSTOMER"), 
    FRAME ("FRAME"),
    PPCO ("PPCO"),
    STANDARD ("STANDARD"),
    W_RED ("W-RED"),
    LEGACY("LEGACY"),
    OPTIONB ("OPTIONB");

 private final String cosProfileType;

 private CosProfileType(String s) {
     cosProfileType = s;
    }

    public boolean equalsName(String otherName){
        return (otherName == null)? false:cosProfileType.equals(otherName);
    }

    public String toString(){
       return cosProfileType;
    }
  }
}

我为我的枚举类型CosProfileType创建了一个测试用例,但是在CosProfileType上遇到了错误。我该如何使此测试用例正常工作?

@Test
   public void testAdd() {
    TrafficProfileExtension ext = new TrafficProfileExtension();
    assertEquals("FRAME", ext.CosProfileType.FRAME);

}

2
你想要测试哪些功能? - Elliott Frisch
你在断言一个 String 等于一个 enum 实例。那么 ext 是什么? - Boris the Spider
我在 CosProfileType 上遇到错误 :| - Sotirios Delimanolis
3个回答

21

由于CosProfileType被声明为public static,因此它实际上是一个顶级类(枚举),因此您可以执行以下操作:

assertEquals("FRAME", CosProfileType.FRAME.name());

值得注意的是,enum 总是一个静态嵌套类 - 它不能是内部类。在这种情况下,static 修饰符是多余的... - Boris the Spider

3

您正在将一个永远不会相等的Enum与一个String进行比较。

请尝试:

@Test
public void testAdd() {
    TrafficProfileExtension ext = new TrafficProfileExtension();
    assertEquals("FRAME", ext.CosProfileType.FRAME.toString());

}

尝试使用assertEquals("FRAME", CosProfileType.FRAME.toString()); - user4910279

1
assertEquals("FRAME", CosProfileType.FRAME.name());

它只在字段和值完全相同时才起作用,但对以下情况不起作用:

FRAME ("frame_value")

最好检查一下。
assertEquals("FRAME", CosProfileType.FRAME.getFieldName());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接