What do you do with methods that throw exceptions in jUnit tests? As you see the addAnswer
method in the Question
class may throw a exception. In the shouldFailifTwoAnswerAreCorrect
method I want to check if the exception is thrown but in the shouldAddAnswersToQuestion
Should I add throws MultipleAnswersAreCorrectException
from the private addAnswerToQuestion
method and try/catch in the shouldAddAnswersToQuestion
or throw it in that method too?
What do you do when methods throw exception(s) in tests?
public class QuestionTest {
private Question question;
@Before
public void setUp() throws Exception {
question = new Question("How many wheels are there on a car?", "car.png");
}
@Test
public void shouldAddAnswersToQuestion() {
addAnswerToQuestion(new Answer("It is 3", false));
addAnswerToQuestion(new Answer("It is 4", true));
addAnswerToQuestion(new Answer("It is 5", false));
addAnswerToQuestion(new Answer("It is 6", false));
assertEquals(4, question.getAnswers().size());
}
@Test(expected = MultipleAnswersAreCorrectException.class)
public void shouldFailIfTwoAnswersAreCorrect() {
addAnswerToQuestion(new Answer("It is 3", false));
addAnswerToQuestion(new Answer("It is 4", true));
addAnswerToQuestion(new Answer("It is 5", true));
addAnswerToQuestion(new Answer("It is 6", false));
}
private void addAnswerToQuestion(Answer answer) {
question.addAnswer(answer);
}
}
Method in Question class
public void addAnswer(Answer answer) throws MultipleAnswersAreCorrectException {
boolean correctAnswerAdded = false;
for (Answer element : answers) {
if (element.getCorrect()) {
correctAnswerAdded = true;
}
}
if (correctAnswerAdded) {
throw new MultipleAnswersAreCorrectException();
} else {
answers.add(answer);
}
}