Is it possible to have enumeration values as private static final constants in Java?

worldOfCompSci :

Is it possible to have enumeration values as private static final constants in Java?

I am currently writing an IssueTest class for the Issue class. In the Issue class, I have an inner enumeration for the type of Issue, which may be a bug or enhancement.

public enum IssueType {
        ENHANCEMENT,
        BUG;
}

In one of the constructors for an Issue, one of the parameters is the IssueType.

public Issue(IssueType type, String state, String summary) {

}

I am trying to write a case to test this constructor. In my test class, I have tried to create a constant for the IssueTypes like so

private static final IssueType TYPE_BUG = BUG;  
private static final IssueType TYPE_ENHANCEMENT = ENHANCEMENT;

But these lines are creating compiler errors. I am not sure how to use an IssueType constant in my test class to test the constructors. Any guidance is greatly appreciated!

kriegaex :

As others have said before, you should not create redundant static final members inside your test, but if you insist you can. If done correctly, there should not be any compiler error.

My little MCVE shows how to do both, using redundant static fields and elegantly using the enumeration constants directly:

package de.scrum_master.stackoverflow.q60556923;

public class Issue {
  public enum IssueType {
    ENHANCEMENT,
    BUG
  }

  public Issue(IssueType type, String state, String summary) {}
}
package de.scrum_master.stackoverflow.q60482676;

import de.scrum_master.stackoverflow.q60556923.Issue.IssueType;
import org.junit.Test;

import static de.scrum_master.stackoverflow.q60556923.Issue.IssueType.*;
import static org.junit.Assert.assertEquals;

public class IssueTest {
  // Seriously?! Nah, rather not.
  private static final IssueType TYPE_BUG = BUG;
  private static final IssueType TYPE_ENHANCEMENT = ENHANCEMENT;

  @Test
  public void testUsingStaticFinal() {
    // Does this make anything better or just obfuscate and complicate the test?
    assertEquals("BUG", TYPE_BUG.toString());
    assertEquals("ENHANCEMENT", TYPE_ENHANCEMENT.toString());
  }

  @Test
  public void testUsingEnumDirectly() {
    assertEquals("BUG", BUG.toString());
    assertEquals("ENHANCEMENT", ENHANCEMENT.toString());
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=28904&siteId=1