Marcelo Paiva Fontes
Marcelo Paiva Fontes

Reputation: 25

Testing a Condtional Based on Enum

Should I test every condition in unit test when the conditional is based on a method of an enum?

I mean if I have an enum with a lot of values, the unit test gets too big to reach all possible conditions.

Example:

public enum AnEnum {
   A(true), B(false), C(false), D(true);

   AnEnum(boolean isError) {
       this.isError = isError
   }
}

public class TestEnum {
    public String method(AnEnum anEnum) {
         if( anEnum.isError() ) {
              return "An Error";
         }
         return "Not An Error";
    }
}

Upvotes: 1

Views: 635

Answers (2)

Michal Kordas
Michal Kordas

Reputation: 10925

Data-driven tests are great with Spock:

class AnEnumSpec extends Specification {

    def "has correct error status"() {
        expect:
        result == anEnum.isError

        where:
        anEnum   | result
        AnEnum.A | true
        AnEnum.B | false
        AnEnum.C | false
        AnEnum.D | true
    }
}

Upvotes: 0

GhostCat
GhostCat

Reputation: 140457

You could be using ParametrizedTests, like:

@DataProvider
public static Object[][] provideEnumasAndExpectedErrorResult() {
  return new Object[][] {
    { AnEnum.A, true },
    { AnEnum.B, false }
  };
}

@Test
@UseDataProvider( "provideEnumasAndExpectedErrorResult" )
public void testEnumErrors( AnEnum enumConstant, boolean expectedResult expectedResult ) {
  assertThat( enumConstant.isError(), is(expectedResult));

That allows you to write down all your enums and the expected results in a (somehow) cleaner way.

Upvotes: 1

Related Questions