Reputation: 43
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;
}
}
Upvotes: 4
Views: 1681
Reputation: 24520
Your fields are an internal state of the objects. You should only test the class' behavior to the outside world. The fields' values cause some external behavior of QuizAnswer
, which should be tested. E.g. if you have a method that checks whether an option is the answer:
@Test
public void first_option_is_the_answer_when_ans1_flag_is_true() {
QuizAnswer answer = new QuizAnswer(true, false, false, false);
boolean firstOptionIsAnswer = answer.isNthOptionTheAnswer(1);
assertTrue(firstOptionIsAnswer);
}
You may have a look at JUnit's Parameterized runner, because you may want to write data driven tests.
Upvotes: 3
Reputation: 2821
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
Upvotes: 3