对于在jUnit测试中抛出异常的方法,您如何处理?如您所见 Question
类中的 addAnswer
方法可能会抛出异常 . 在 shouldFailifTwoAnswerAreCorrect
方法中,我想检查是否抛出了异常,但在 shouldAddAnswersToQuestion
中
我应该从私有 addAnswerToQuestion
方法添加抛出 MultipleAnswersAreCorrectException
并在_2474623中尝试/ catch还是在该方法中抛出它?
当方法在测试中抛出异常时,你会怎么做?
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);
}
}
2 回答
您必须将
throws
声明添加到addAnswerToQuestion
然后尝试/捕获异常或使用expected
属性或@Test
:在
shouldAddAnswersToQuestion
测试如果你不期望MultipleAnswersAreCorrectException
然后你可以在try / catch中包围该块并写一个断言失败条件,例如我认为最好让测试失败,而不是从测试中抛出异常,因为所有的测试都应该失败,因为assertin失败而不是因为异常 .