How to unit test a class with multiple boolean fields Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to unit test a class with multiple boolean fields without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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;


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);
// Then for next:
QuizAnswer secondTrue = QuizAnswer(false, true, false, false);
// Etc. You could also check if all other answers are false
We are here to answer your question about How to unit test a class with multiple boolean fields - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji