سؤال

هل هناك ما يعادل ExpectedException NUnit أو Assert.Throws <> في أداة JUnit؟

هل كانت مفيدة؟

المحلول

وjunit4:

@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
    getFile(null);
}

وjunit3:

void testShouldThrowException() {
    try {
      getFile(null);
      fail("Expected Exception DocumentException");
    } catch(DocumentException e) {}
}

نصائح أخرى

وكنت قد تنظر أيضا أن نلقي نظرة على الطبقة ExpectedException الذي يوفر أكثر ثراء مطابقة استثناء.

https://github.com/junit-team/junit/wiki / استثناء اختبار

وليس فقط يمكنك أن تطابق الطبقة استثناء ولكن أيضا يمكنك تطبيق matchers مخصص لرسالتها.

إذا كنت تستخدم رائع لJUnit الاختبارات الخاصة بك يمكنك استخدام <لأ href = "http://groovy.codehaus.org/gapi/groovy/util/GroovyTestCase.html#shouldFail٪28groovy.lang.Closure٪29" يختلط = "نوفولو"> shouldFail .

وهنا مثال باستخدام أسلوب junit3:

void testShouldThrowException() {
    def message = shouldFail(DocumentException) {
        documentService.getFile(null)
    }
    assert message == 'Document could not be saved because it ate the homework.'
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top