1

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";
    }
}
Andrew Lygin
  • 6,077
  • 1
  • 32
  • 37
  • Possibly of interest [how to test enum types](http://stackoverflow.com/questions/1079700/how-to-test-enum-types). Also [data-driven-testing](https://spockframework.github.io/spock/docs/1.0/data_driven_testing.html) may be helpful, and not only for your enum but for cases which require it. – Morfic Aug 25 '16 at 18:36
  • 1
    What is the point of testing getters and setters? Are you testing Java? Limit your test to things with actual logic in it. See [Should unit tests be written for getter and setters?](http://stackoverflow.com/q/6197370/5221149) – Andreas Aug 25 '16 at 18:45
  • This is not about to test setters and getters. It is about to test all possible combination in your code. Should we test all combinations or should we test just 2 combinations ( in the example your can have 100% code coverage with only 2 combinations while your code can have a lot more combinations ) – Marcelo Paiva Fontes Sep 01 '16 at 16:37
  • Thanks for the accept ;-) – GhostCat May 22 '17 at 17:36

2 Answers2

1

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • I apologize if you already knew, but depending on your licenses restrictions, you could also use these 2 extensions which make thinks cleaner and more elegant: [zohhak](https://github.com/piotrturski/zohhak) (LGPL 3.0) & [JUnitParams](https://github.com/Pragmatists/JUnitParams) (Apache 2.0) – Morfic Aug 25 '16 at 19:21
0

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
    }
}
Michal Kordas
  • 10,475
  • 7
  • 58
  • 103