Java 如何使用 JUNIT 测试 ENUM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32150174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:05:07  来源:igfitidea点击:

How to test ENUMs using JUNIT

javajunitenums

提问by yesco1

How can I create test cases using JUNIT to test ENUMS types. Below I added my code with the enum type.

如何使用 JUNIT 创建测试用例来测试 ENUMS 类型。下面我用 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;
    }
  }
}

I created a test case for my enum CosProfileType, and I am getting an error on CosProfileType.How can I make this test case work?

我为 enum 创建了一个测试用例CosProfileType,但在 CosProfileType 上出现错误。如何使这个测试用例工作?

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

}

采纳答案by Reimeus

Since CosProfileTypeis declared public staticit is effectively a top level class (enum) so you could do

由于CosProfileType被声明public static它实际上是一个顶级类(枚举)所以你可以做

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

回答by jbarrueta

You are comparing and Stringto an Enumthat will never be equal.

您比较和String一个Enum永远不会是平等的。

Try:

尝试:

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

}