More Related Content
Similar to Junit for method_throwing_exception (6)
Junit for method_throwing_exception
- 1. 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);
}
}
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);
}
}