Luc*_*uke 0 java junit exception java-ee
对于在jUnit测试中抛出异常的方法,您如何处理?如您所见,该类中的addAnswer方法Question可能会抛出异常.在shouldFailifTwoAnswerAreCorrect方法中,我想检查是否抛出了异常,但是在shouldAddAnswersToQuestion
我应该MultipleAnswersAreCorrectException从私有addAnswerToQuestion方法中添加throws 并尝试/ catch 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);
}
}
Run Code Online (Sandbox Code Playgroud)
问题类中的方法
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);
}
}
Run Code Online (Sandbox Code Playgroud)
你必须添加throws声明addAnswerToQuestion然后尝试/捕获异常或使用expected属性或@Test:
@Test(expected=IOException.class)
public void test() {
// test that should throw IOException to succeed.
}
Run Code Online (Sandbox Code Playgroud)