When methods are throwing exceptions in jUnit
对于在jUnit测试中抛出异常的方法,您如何处理? 如您所见,
我应该从私有
当方法在测试中抛出异常时,你会怎么做?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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); } } |
问题类中的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); } } |
您必须将
1 2 3 4 | @Test(expected=IOException.class) public void test() { // test that should throw IOException to succeed. } |
在
1 2 3 4 5 6 7 8 9 10 11 12 | @Test public void shouldAddAnswersToQuestion() { try{ 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()); }catch(MultipleAnswersAreCorrectException e){ Assert.assertFail("Some self explainable failure statement"); } } |
我认为最好让测试失败,而不是从测试中抛出异常,因为所有的测试都应该失败,因为assertin失败而不是因为异常。