我有一个枚举和一个对象,我想在junit测试中验证其唯一性。

例如,我有一个枚举颜色,如下所示:

 public enum Colors{

    Yellow("This is my favorite color"),
    Blue("This color is okay"),
    Orange("I do not like this color"),
    Green("I hate this color");

    private String value;

    Colors(String value) {
        this.value = value;
    }

    public String getDescription() {
        return value;
    }
}


我还有一个名为ColorList的ArrayList,它包含具有两个属性的Color对象:value和description。我想验证ColorList来测试是否有四个Color对象包含枚举中的值。如果以下任何一种情况,我希望测试失败:


枚举中存在一个不在arrayList中的值
arrayList中存在一个不在Enum中的值

最佳答案

我认为您可以使用EnumSet做您最想要的事情。这将确保您一次拥有所有颜色,并且仅此一次。

EnumSet<Colors> allColors = EnumSet.allOf(Colors.class);


这是我的工作,以防万一:

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.EnumSet;

import org.junit.Test;

public class TempTest {

    @Test
    public void x() {
        EnumSet<Colors> allColors = EnumSet.allOf(Colors.class);
        assertEquals(4, allColors.size());
        assertThat(allColors, contains(Colors.Yellow, Colors.Blue, Colors.Orange, Colors.Green));
        for (Colors c : allColors) {
            System.out.println(c.name() + " (" + c.getDescription() + ")");
        }
    }
}


出现绿色条并打印:

Yellow (This is my favorite color)
Blue (This color is okay)
Orange (I do not like this color)
Green (I hate this color)


顺便说一下,我在Eclipse中遇到了一个编译错误:您的枚举值列表以逗号而不是分号结尾。

另外,从风格上讲,我不知道您是否可以更改枚举,但是,如果可以,Java中的常规约定是在ALL_CAPS中具有枚举值并设置枚举类名称单数(而不是复数)-例如您可以将其称为public enum NamedColor { YELLOW, RED; }。您也可以将value重命名为description以使其用途更清楚。

09-29 22:16