English 中文(简体)
你们怎么说,在Junnit测试中出现了某种例外?
原标题:How do you assert that a certain exception is thrown in JUnit tests?

我怎么能用日本特尼特语检验一下某些法典是否提出了例外?

我当然可以这样做:

@Test
public void testFooThrowsIndexOutOfBoundsException() {

    boolean thrown = false;

    try {
        foo.doStuff();
    } catch (IndexOutOfBoundsException e) {
        thrown = true;
    }

    assertTrue(thrown);
}

我回顾,有说明或“Assert.xyz”或“thing,就这些局势而言,这种说明或说明远不如舒服,而日本特尼特的间谍更远。

最佳回答

It depends on the JUnit version and what assert libraries you use.

<代码>JUnit <=4.12的原始答复是:

    @Test(expected = IndexOutOfBoundsException.class)
    public void testIndexOutOfBoundsException() {

        ArrayList emptyList = new ArrayList();
        Object o = emptyList.get(0);

    }

https://stackoverflow.com/a/31826781/2986984>answer 可供Junnit <选择的方案;=4.12。

Reference:

问题回答

Edit: Now that JUnit 5 and JUnit 4.13 have been released, the best option would be to use Assertions.assertThrows() (for JUnit 5) and Assert.assertThrows() (for JUnit 4.13+):

@Test
void exceptionTesting() {
    Exception exception = assertThrows(ArithmeticException.class, () ->
        calculator.divide(1, 0));
    assertEquals("/ by zero", exception.getMessage());
}

详见https://stackoverflow.com/a/46514550/95725” 。

If you haven t migrated to JUnit 5, but can use JUnit 4.7, you can use the ExpectedException Rule:

public class FooTest {
  @Rule
  public final ExpectedException exception = ExpectedException.none();

  @Test
  public void doStuffThrowsIndexOutOfBoundsException() {
    Foo foo = new Foo();

    exception.expect(IndexOutOfBoundsException.class);
    foo.doStuff();
  }
}

这比 试验(expected=IndexOutOfBoundsException.qu)好得多。 由于如果<代码>测试将失败 索引OutOfBoundsException在foo.doStuff(前被推翻。

See this article for details.

谨慎使用预期的例外,因为它只声称method。 在试验中添加这一例外,而不是“部分代码

I tend to use this for testing parameter validation, because such methods are usually very simple, but more complex tests might better be served with:

try {
    methodThatShouldThrow();
    fail( "My method didn t throw when I expected it to" );
} catch (MyException expectedException) {
}

判决。

在陪审团中,有四种检验例外的方法。

junit5.x

  • 页: 1 简称表

    @Test
    public void testFooThrowsIndexOutOfBoundsException() {
        Throwable exception = assertThrows(IndexOutOfBoundsException.class, () -> foo.doStuff());
        assertEquals("expected messages", exception.getMessage());
    }
    

junit4.x

  • 用于使用试验放弃的任择预期属性

    @Test(expected = IndexOutOfBoundsException.class)
    public void testFooThrowsIndexOutOfBoundsException() {
        foo.doStuff();
    }
    
  • 供法官使用的预期接收规则

    public class XxxTest {
        @Rule
        public ExpectedException thrown = ExpectedException.none();
    
        @Test
        public void testFooThrowsIndexOutOfBoundsException() {
            thrown.expect(IndexOutOfBoundsException.class)
            //you can test the exception message like
            thrown.expectMessage("expected messages");
            foo.doStuff();
        }
    }
    
  • 您也可使用第3号大法官框架内广泛使用的经典审判/渔获法。

    @Test
    public void testFooThrowsIndexOutOfBoundsException() {
        try {
            foo.doStuff();
            fail("expected exception was not occured.");
        } catch(IndexOutOfBoundsException e) {
            //if execution reaches here, 
            //it indicates this exception was occured.
            //...... we need not handle it.
        }
    }
    
  • ......

    • if you like junit 5, then you should like the 1st one
    • the 2nd way is used when you only want test the type of exception
    • the first and last two are used when you want test exception message further
    • if you use junit 3, then the 4th one is preferred
  • 欲了解更多信息,可读到

http://www.ohchr.org。

  • The post-JDK8 : Use AssertJ or Customs lambdas to claim Tenional conduct.

  • “JDK8”前:我将建议在<条码>上添加<条码>的>条码>。

Regardless of Junit 4 or JUnit 5.

<>长篇>

可在<>上填写。 (@) 测试(expected = ......)@ Rules 预期Exception 日美特统治特征。

但是,这些方法并不十分合法,没有与其他工具相混合。 此外,Junnit工具的确有一些陷阱。

  1. http://www.un.org/Depts/DGACM/index_french.htm 阻止你在测试行为周围穿透镜头,并写在渔获区的说法,这种说法可能是罚款,但许多人发现,这种风格干扰了测试的读流。 另外,在<条码>、<>条码/代码>栏目末,您必须写上<条码>。 否则,测试可能会误导断言的一方;PMD,findbugSonar将发现这些问题。

  2. The @Test(expected = ...) feature is interesting as you can write less code and then writing this test is supposedly less prone to coding errors. But this approach is lacking in some areas.

    • If the test needs to check additional things on the exception like the cause or the message (good exception messages are really important, having a precise exception type may not be enough).
    • 另外,由于这一期望被放在方法上,取决于所测试的代码是如何书写的,因此测试法的错误部分可以放弃这一例外,导致错误的检验,而Im则不能确定,PMD,findbugsSonar将就这种守则提供背后的内容。

      @Test(expected = WantedException.class)
      public void call2_should_throw_a_WantedException__not_call1() {
          // init tested
          tested.call1(); // may throw a WantedException
      
          // call to be actually tested
          tested.call2(); // the call that is supposed to raise an exception
      }
      
  3. www.un.org/Depts/DGACM/index_french.htm 规则也是试图确定先前的警告,但认为使用期望风格的比喻是难得的。 用户非常了解这种风格。 某些人可能方便,但如果你遵循Behaviourn Development(BDD)或Arrange Act Assert(AAAA)原则,ExpectedException 规则就赢得了适合这些写作风格的证书。 除此以外,它还可能遇到与<代码>@相同的问题。 测试方法,视您的期望所在。

    @Rule ExpectedException thrown = ExpectedException.none()
    
    @Test
    public void call2_should_throw_a_WantedException__not_call1() {
        // expectations
        thrown.expect(WantedException.class);
        thrown.expectMessage("boom");
    
        // init tested
        tested.call1(); // may throw a WantedException
    
        // call to be actually tested
        tested.call2(); // the call that is supposed to raise an exception
    }
    

    即使在测试说明之前,如果测验遵循BDD或AAA,它也会打破阅读流。

    另见commentJUnit 4.13-beta-2

    https://github.com/junit-team/junit4/pull/1519”rel=“noreferer”> Pull request #1519: Deprecate 预期Exception

    方法 Assert.assert 浏览器为核查例外提供了更nic的方法。 此外,使用预期外观在使用其他规则(例如:测试Watcher)时容易发生错误,因为在这种情况下,规则的次序很重要。

因此,上述选择具有所有加固剂的载荷,而且显然无法避免编码错误。

  1. There s a project I became aware of after creating this answer that looks promising, it s catch-exception.

    正如对项目的说明所述,它让一位编码员在符合例外情形的行文中写字,并对后者的说法提出这一例外。 也可使用任何主张图书馆,如、HamcrestAssertJ

    快速实例:

    // given: an empty list
    List myList = new ArrayList();
    
    // when: we try to get the first element of the list
    when(myList).get(1);
    
    // then: we expect an IndexOutOfBoundsException
    then(caughtException())
            .isInstanceOf(IndexOutOfBoundsException.class)
            .hasMessage("Index: 1, Size: 0") 
            .hasNoCause();
    

    由于你可以看到该守则是真的直截了当的,你在具体行文上就把该例外排在了上,因此,thenAPIC是使用AssertJ AP(类似于使用assertThat(ex).NoCause()。 At some point the project based on FEST-Assert the ancestor of AssertJ. http://www.un.org。 该项目似乎正在bre8 Lambdas支助。

    目前,该图书馆有两个缺陷:

    • 在撰写本报告时,值得注意的是,该图书馆是以Mockito 1.x为基地的,因为它在幕后制造了试验物体的 mo。 由于Mockito尚未更新,该图书馆无法使用最后班级或最后方法。 即使以目前版本中的Mockito 2为基础,这也要求宣布一个全球模拟制造者(inline-mock-maker),这或许不是你想要的,因为这个模拟制造者有不同的缺点,即固定的模拟制造者。

    • 这又需要另一个测试依赖。

    一旦图书馆支持马拉姆达斯,这些问题就获得了适用。 然而,这一功能将由AssertJ工具et复制。

    www.un.org/Depts/DGACM/index_spanish.htm 如果你不希望使用渔获量例外工具,我将建议采用“<条码>、<>条码>-<条码>->(>>>>,至少至于“JDK7”栏。 而对于JD8用户来说,你可能更喜欢使用AssertJ,因为它所提供的服务可能不仅仅是声称有例外。

  2. 有了JDK8,Mlambdas就进入了试验场,证明他们是一种令人感兴趣的方法,可以主张特殊行为。 惯性 对J进行了更新,以提供极易变的APIC来表明特殊行为。

    http://joel-costigliola.github.io/assertj/“rel=“noreferer”>AssertJ :

    @Test
    public void test_exception_approach_1() {
        ...
        assertThatExceptionOfType(IOException.class)
                .isThrownBy(() -> someBadIOOperation())
                .withMessage("boom!"); 
    }
    
    @Test
    public void test_exception_approach_2() {
        ...
        assertThatThrownBy(() -> someBadIOOperation())
                .isInstanceOf(Exception.class)
                .hasMessageContaining("boom");
    }
    
    @Test
    public void test_exception_approach_3() {
        ...
        // when
        Throwable thrown = catchThrowable(() -> someBadIOOperation());
    
        // then
        assertThat(thrown).isInstanceOf(Exception.class)
                          .hasMessageContaining("boom");
    }
    
  3. 5号日元的近完成后,这些断言可能证明是正确的主张。 但是,实际上,APICS仍然是穷人,在>>>>>>>>>>> 专栏。

    @Test
    @DisplayName("throws EmptyStackException when peeked")
    void throwsExceptionWhenPeeked() {
        Throwable t = assertThrows(EmptyStackException.class, () -> stack.peek());
    
        Assertions.assertEquals("...", t.getMessage());
    }
    

    如您注意到的<代码>>assertEquals, 仍在退回, 撤销,因此,t 允许像AssertJ这样的链条主张。

    如果你记住姓名与<条码>(MatcherAssert发生冲突,则准备与<条码>Assertions发生同样的冲突。

我愿得出结论,今天(2017-03-03)AssertJ 方便使用、可发现的APIC、快速发展速度和作为事实上的的测试依赖性,是最佳解决办法,不论试验框架(联合还是非)如何,以前的JDKs应当依靠> ->>、<>ches/code>>、<>/code>、<<>/strong>,即使他们感到ky。

www.un.org/Depts/DGACM/index_spanish.htm 这一回答从 。 我是同一位作者。

Now that JUnit 5 and JUnit 4.13 have been released, the best option would be to use Assertions.assertThrows() (for JUnit 5) and Assert.assertThrows() (for JUnit 4.13). See the JUnit 5 User Guide.

这里的一个例子是,有人 exception弃了一种例外情况,并使用Truth对例外信息作出说明:

public class FooTest {
  @Test
  public void doStuffThrowsIndexOutOfBoundsException() {
    Foo foo = new Foo();

    IndexOutOfBoundsException e = assertThrows(
        IndexOutOfBoundsException.class, foo::doStuff);

    assertThat(e).hasMessageThat().contains("woops!");
  }
}

在其他答复中,这种办法的好处是:

  1. Built into JUnit
  2. You get a useful exception message if the code in the lambda doesn t throw an exception, and a stacktrace if it throws a different exception
  3. Concise
  4. Allows your tests to follow Arrange-Act-Assert
  5. You can precisely indicate what code you are expecting to throw the exception
  6. You don t need to list the expected exception in the throws clause
  7. You can use the assertion framework of your choice to make assertions about the caught exception

<>Update: 日特5改进了例外情况测试:assertThrows

The following example is from: Junit 5 User Guide

import static org.junit.jupiter.api.Assertions.assertThrows;

@Test
void exceptionTesting() {
    IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
        throw new IllegalArgumentException("a message");
    });
    assertEquals("a message", exception.getMessage());
}

www.un.org/Depts/DGACM/index_spanish.htm 初步答案:

有几个办法可以检验存在一种例外。 我还在我的。 • 如何与Junnit进行大单位测试

Set of the expected para amount :Release@(expected = file NotFoundException.class)

@Test(expected = FileNotFoundException.class) 
public void testReadFile() { 
    myClass.readFile("test.txt");
}

采用<条码><%/代码> > 副渔获物/代码>

public void testReadFile() { 
    try {
        myClass.readFile("test.txt");
        fail("Expected a FileNotFoundException to be thrown");
    } catch (FileNotFoundException e) {
        assertThat(e.getMessage(), is("The file test.txt does not exist!"));
    }
     
}

测试ExpectedException 规则。

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void testReadFile() throws FileNotFoundException {
    
    thrown.expect(FileNotFoundException.class);
    thrown.expectMessage(startsWith("The file test.txt"));
    myClass.readFile("test.txt");
}

可在bad.robot - Expecting Statelessnessions JUnit Rule

如何做到这一点:只举一个非常一般的例外,确保它脱离渔获区,然后断言例外的类别是你们期望的。 如果(a) 例外是错的类型(例如,如果你去找Null Pointer,则)和(b) 例外被推倒。

public void testFooThrowsIndexOutOfBoundsException() {
  Throwable e = null;

  try {
    foo.doStuff();
  } catch (Throwable ex) {
    e = ex;
  }

  assertTrue(e instanceof IndexOutOfBoundsException);
}

BDD Style Solution: JUnit 4 + Catch Exception + AssertJ

import static com.googlecode.catchexception.apis.BDDCatchException.*;

@Test
public void testFooThrowsIndexOutOfBoundsException() {

    when(() -> foo.doStuff());

    then(caughtException()).isInstanceOf(IndexOutOfBoundsException.class);

}

Dependencies

eu.codearte.catch-exception:catch-exception:2.0

To solve the same problem I did set up a small project: http://code.google.com/p/catch-exception/

Using this little helper you would write

verifyException(foo, IndexOutOfBoundsException.class).doStuff();

This is less verbose than the ExpectedException rule of JUnit 4.7. In comparison to the solution provided by skaffman, you can specify in which line of code you expect the exception. I hope this helps.

也可以这样做:

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    try {
        foo.doStuff();
        assert false;
    } catch (IndexOutOfBoundsException e) {
        assert true;
    }
}

IMHO是检查日本特尼特的例外情况的最佳途径,是审判/捕获/捕获/扣押。

// this try block should be as small as possible,
// as you want to make sure you only catch exceptions from your code
try {
    sut.doThing();
    fail(); // fail if this does not throw any exception
} catch(MyException e) { // only catch the exception you expect,
                         // otherwise you may catch an exception for a dependency unexpectedly
    // a strong assertion on the message, 
    // in case the exception comes from anywhere an unexpected line of code,
    // especially important if your checking IllegalArgumentExceptions
    assertEquals("the message I get", e.getMessage()); 
}

The assertTrue might be a bit strong for some people, so assertThat(e.getMessage(), containsString("the message"); might be preferable.

JUnit 5 Solution

import static org.junit.jupiter.api.Assertions.assertThrows;

@Test
void testFooThrowsIndexOutOfBoundsException() {    
  IndexOutOfBoundsException exception = expectThrows(IndexOutOfBoundsException.class, foo::doStuff);
     
  assertEquals("some message", exception.getMessage());
}

More Infos about JUnit 5 on http://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions

我在此尝试了许多方法,但是这些方法要么复杂,要么没有达到我的要求。 事实上,可以简单地写出一种帮助方法:

public class ExceptionAssertions {
    public static void assertException(BlastContainer blastContainer ) {
        boolean caughtException = false;
        try {
            blastContainer.test();
        } catch( Exception e ) {
            caughtException = true;
        }
        if( !caughtException ) {
            throw new AssertionFailedError("exception expected to be thrown, but was not");
        }
    }
    public static interface BlastContainer {
        public void test() throws Exception;
    }
}

如此:

assertException(new BlastContainer() {
    @Override
    public void test() throws Exception {
        doSomethingThatShouldExceptHere();
    }
});

零依赖性:不需要 mo子,不需要电磁;只用最后班子做罚款。

在我的案件中,我总是从 d带走,但电文不同。 需要分别处理例外情况。 这里我是如何测试的:

@Test
public void testThrowsExceptionWhenWrongSku() {

    // Given
    String articleSimpleSku = "999-999";
    int amountOfTransactions = 1;
    Exception exception = null;

    // When
    try {
        createNInboundTransactionsForSku(amountOfTransactions, articleSimpleSku);
    } catch (RuntimeException e) {
        exception = e;
    }

    // Then
    shouldValidateThrowsExceptionWithMessage(exception, MESSAGE_NON_EXISTENT_SKU);
}

private void shouldValidateThrowsExceptionWithMessage(final Exception e, final String message) {
    assertNotNull(e);
    assertTrue(e.getMessage().contains(message));
}

仅让一个能够被击退的牵线搭桥者,就如:

public class ExceptionMatcher extends BaseMatcher<Throwable> {
    private boolean active = true;
    private Class<? extends Throwable> throwable;

    public ExceptionMatcher(Class<? extends Throwable> throwable) {
        this.throwable = throwable;
    }

    public void on() {
        this.active = true;
    }

    public void off() {
        this.active = false;
    }

    @Override
    public boolean matches(Object object) {
        return active && throwable.isAssignableFrom(object.getClass());
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("not the covered exception type");
    }
}

使用:

add public ExpectedException exception = ExpectedException.none();, then:

ExceptionMatcher exMatch = new ExceptionMatcher(MyException.class);
exception.expect(exMatch);
someObject.somethingThatThrowsMyException();
exMatch.off();

在日本四国或之后,你可以测试以下例外情况:

@Rule
public ExpectedException exceptions = ExpectedException.none();

www.un.org/Depts/DGACM/index_spanish.htm这提供了许多特点,可用于改进我们的日元测试。 www.un.org/Depts/DGACM/index_spanish.htm 如果你看到以下例子,我正在测试3件例外情况。

  1. The Type of exception thrown
  2. The exception Message
  3. The cause of the exception

www.un.org/Depts/DGACM/index_spanish.htm

public class MyTest {

    @Rule
    public ExpectedException exceptions = ExpectedException.none();

    ClassUnderTest classUnderTest;

    @Before
    public void setUp() throws Exception {
        classUnderTest = new ClassUnderTest();
    }

    @Test
    public void testAppleisSweetAndRed() throws Exception {

        exceptions.expect(Exception.class);
        exceptions.expectMessage("this is the exception message");
        exceptions.expectCause(Matchers.<Throwable>equalTo(exceptionCause));

        classUnderTest.methodUnderTest("param1", "param2");
    }

}

We can use an assertion fail after the method that must return an exception:

try{
   methodThatThrowMyException();
   Assert.fail("MyException is not thrown !");
} catch (final Exception exception) {
   // Verify if the thrown exception is instance of MyException, otherwise throws an assert failure
   assertTrue(exception instanceof MyException, "An exception other than MyException is thrown !");
   // In case of verifying the error message
   MyException myException = (MyException) exception;
   assertEquals("EXPECTED ERROR MESSAGE", myException.getMessage());
}

此外, 说了,确保:

Do <>strong>not do this:

@Rule    
public ExpectedException expectedException;

@Before
public void setup()
{
    expectedException = ExpectedException.none();
}

最后,

Junit4办法与Java8共同使用这一功能:

public Throwable assertThrows(Class<? extends Throwable> expectedException, java.util.concurrent.Callable<?> funky) {
    try {
        funky.call();
    } catch (Throwable e) {
        if (expectedException.isInstance(e)) {
            return e;
        }
        throw new AssertionError(
                String.format("Expected [%s] to be thrown, but was [%s]", expectedException, e));
    }
    throw new AssertionError(
            String.format("Expected [%s] to be thrown, but nothing was thrown.", expectedException));
}

然后使用:

    assertThrows(ValidationException.class,
            () -> finalObject.checkSomething(null));

Note that the only limitation is to use a final object reference in lambda expression. This solution allows to continue test assertions instead of expecting thowable at method level using @Test(expected = IndexOutOfBoundsException.class) solution.

I recomend Library assertj-分,以处理黄麻测试中的例外情况

在java 8月,情况如下:

//given

//when
Throwable throwable = catchThrowable(() -> anyService.anyMethod(object));

//then
AnyException anyException = (AnyException) throwable;
assertThat(anyException.getMessage()).isEqualTo("........");
assertThat(exception.getCode()).isEqualTo(".......);

页: 1

@Test
public void testFooThrowsIndexOutOfBoundsException() {
  assertThatThrownBy(() -> doStuff()).isInstanceOf(IndexOutOfBoundsException.class)
}

要求AssertJ——参考文件:

Take for example, you want to write Junit for below mentioned code fragment

public int divideByZeroDemo(int a,int b){

    return a/b;
}

public void exceptionWithMessage(String [] arr){

    throw new ArrayIndexOutOfBoundsException("Array is out of bound");
}

以上准则是检验可能出现的一些不为人知的例外情形,而以下一种情况是,除习俗信息外,还要提出某些例外。

 @Rule
public ExpectedException exception=ExpectedException.none();

private Demo demo;
@Before
public void setup(){

    demo=new Demo();
}
@Test(expected=ArithmeticException.class)
public void testIfItThrowsAnyException() {

    demo.divideByZeroDemo(5, 0);

}

@Test
public void testExceptionWithMessage(){


    exception.expectMessage("Array is out of bound");
    exception.expect(ArrayIndexOutOfBoundsException.class);
    demo.exceptionWithMessage(new String[]{"This","is","a","demo"});
}

With 8位阁下可以制定一种方法,将守则作为参数加以核对和预期的例外:

private void expectException(Runnable r, Class<?> clazz) { 
    try {
      r.run();
      fail("Expected: " + clazz.getSimpleName() + " but not thrown");
    } catch (Exception e) {
      if (!clazz.isInstance(e)) fail("Expected: " + clazz.getSimpleName() + " but " + e.getClass().getSimpleName() + " found", e);
    }
  }

之后在您的检验中:

expectException(() -> list.sublist(0, 2).get(2), IndexOutOfBoundsException.class);

福利:

  • not relying on any library
  • localised check - more precise and allows to have multiple assertions like this within one test if needed
  • easy to use




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...