1

I have a class that contains several boolean flags that affect how the program behaves, and I want to test that no combination of those flags causes any unexpected behavior. Since there are 2^n possible combinations, I don't want to write all of those test cases. Would it be an appropriate use of reflection to iterate over those flags to generate all possible conditions? The alternative seems to me to be only to test those edge cases which seem most likely to cause issues, which I think puts too much stock in my ability to predict bugs.

Also, could you give me an idea of what that might look like in Java? While I'm familiar with the idea, this would be my first use of reflection. All of my flags have getters and setters so it shouldn't matter, but they're currently backed by bit fields, and after my tests are in place I intend to convert them to be backed by EnumSets.

TBridges42
  • 1,849
  • 1
  • 19
  • 29
  • http://stackoverflow.com/questions/2811141/is-it-bad-practice-to-use-reflection-in-unit-testing – eleven Jul 07 '15 at 13:02
  • I'm not in this case using reflection to get around access restrictions, but to iterate over my setters. I suppose I could instead create a method `setFlag(int flag)`, and an Enum of all the possible flag values, and iterate over that. That actually sounds like a good idea, but now I still need a use case to teach myself reflection. – TBridges42 Jul 07 '15 at 13:51

1 Answers1

0

From you question,I don't think you would really need reflection to do the testing.

1) You may need to have a properties file/csv / Excel with the various combinations of the booleans for the class.Say if your class contains 20 fields which holds boolean values,your excel will contain 20 columns and the number of rows would be the possible number of combinations.

2) Write a util class to read the excel/csv/properties file and dynamically create object of the target class, set the boolean fields of the class and also other fields (map to corresponding enums )and use this instance for your unit testing.

3) you can loop over the rows and cover all the possible combinations.

KDP
  • 1,481
  • 7
  • 13
  • Fortunately I don't have 20 fields, but I think your example of 20 fields is a good demonstration of why I don't want to go this route. 20 boolean fields would have 1,048,576 possible combinations, which is the maximum number of rows Excel can handle. https://support.office.com/en-us/article/Excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 – TBridges42 Jul 07 '15 at 13:38
  • you can have a util method to create all the combinations and populate the csv/excel.Automation is the way to go :-) – KDP Jul 07 '15 at 13:54