Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test ENUMs using JUNIT

Tags:

java

enums

junit

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

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?

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

}
like image 518
yesco1 Avatar asked Aug 21 '15 22:08

yesco1


People also ask

Can you use == for enums?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

Can you mock an enum with Mockito?

Mockito 2 supports mocking of enum, but it is experimental feature. It needs to be enabled explicitly.

How do you create an enum object in Java?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).


1 Answers

Since CosProfileType is declared public static it is effectively a top level class (enum) so you could do

assertEquals("FRAME", CosProfileType.FRAME.name());
like image 107
Reimeus Avatar answered Oct 09 '22 18:10

Reimeus