【发布时间】:2012-02-19 15:07:09
【问题描述】:
您如何处理在 jUnit 测试中引发异常的方法?如您所见,Question 类中的addAnswer 方法可能会引发异常。在shouldFailifTwoAnswerAreCorrect 方法中我想检查是否抛出异常,但在shouldAddAnswersToQuestion 中
我应该从私有 addAnswerToQuestion 方法中添加 throws MultipleAnswersAreCorrectException 并在 shouldAddAnswersToQuestion 中尝试/捕获,还是也应该在该方法中抛出它?
当方法在测试中抛出异常时你会怎么做?
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);
}
}
【问题讨论】:
标签: java exception jakarta-ee junit