Search code examples
javajunit4

How to unit test a class with multiple boolean fields


Sorry if this is a dumb question. I'd like to unit test the following class (there's more to the class but I stripped it down to illustrate my question).

The class consists of multiple boolean fields that get assigned in the constructor.

When I'm unit testing how can I test the parameters are assigned to the correct class field e.g. ans1 -> mIsOption1Ans ?

For example if I assert that all the class fields are "true" this will not identify if another developer has accidentally swapped the assignment in the constructor and assigned a parameter to the wrong class field. I'd like to test that "ans1" always gets assigned to "mIsOption1Ans", etc, etc

public class MultipleChoiceQuizAnswer {
   private Boolean mIsOption1Ans,mIsOption2Ans,mIsOption3Ans,mIsOption4Ans;

   public QuizAnswer (Boolean ans1,Boolean ans2, Boolean ans3,Boolean ans4) {
         mIsOption1Ans = ans1;
         mIsOption2Ans = ans2;
         mIsOption3Ans = ans3;
         mIsOption4Ans = ans4;
    }
}

Solution

  • This is really obvious thing but if you really want to test it you can test for each situation where 1 boolean is true and rest are false.

    So for example:

    QuizAnswer firstTrue = QuizAnswer(true, false, false, false);
    assertTrue(firstTrue.isFirstAnswer());
    // Then for next:
    QuizAnswer secondTrue = QuizAnswer(false, true, false, false);
    assertTrue(secondTrue.isSecondAnswer());
    // Etc. You could also check if all other answers are false