Home > Net >  Came across this enum and have questions about objects and enums in general
Came across this enum and have questions about objects and enums in general

Time:10-20

I have a the following code for setting up availability per region -

enum Region {
    UK,
    US,
    EU;
    private final double availability;

    Region() {
        this.availability = 1;        //constructor 1
    }

    Region(double availability) { //constructor 2
        this.availability = availability;
    }

    public double getAvailability() { //getter
        return this.availability;
    }
}

I'm writing test cases for the above code to test the constructors as below -

@Test
void testConstructor1() {
assertEquals(1, Region.UK.getAvailability())
}

I'm confused how to write the test case for second constructor as enums cannot have objects created like classes.

@Test
void testConstructor2(){
HERE WE CANNOT CREATE AN OBJECT TO PASS THE VALUE THE TEST CONSTRUCTOR 2 RIGHT? 

How can I solve this?

If it's a class we can simply create object and pass in the value and test it.

Please take time in answering the questions below -

  1. Can enums have objects created like classes? 2.Is there any alternative way that can be achieved similar to objects?

CodePudding user response:

The enum constants UK, US, EU are objects of the enum Region. They are created by calling the parameterless constructor. You can think of them as static final fields:

public static final Region UK = new Region();
public static final Region US = new Region();
public static final Region EU = new Region();

So to create more Region objects, you can just declare more enum constants. Since you want to test the second constructor:

public enum Region {
    UK,
    US,
    EU,

    SOMEWHERE_ELSE(10),
    // think of this as:
    // public static final Region SOMEWHERE_ELSE = new Region(10);

    ANOTHER_PLACE(5);
    // this of this as:
    // public static final Region ANOTHER_PLACE = new Region(5);

    // ...
}

Notice that this is the only way to create new objects of enums, which is why a defining property of enum classes is that they can only have a fixed number of instances.

Now you can test that the second constructor actually assigned the available correctly by checking getAvailability:

assertEquals(10, Region.SOMEWHERE_ELSE.getAvailability());
assertEquals(5, Region.ANOTHER_PLACE.getAvailability());

CodePudding user response:

You can't test it, and you don't need to. You only need to test code that might get used elsewhere, and enum constructors can't be.

All you need to do is test each enum value to ensure that it has the right values.

  • Related