如何编写自定义JUnit断言的测试?

时间:2017-08-02 15:45:00

标签: unit-testing junit assertion

我们说我创建了自己的assertSomething(...)方法。如何编写单元测试以验证它是否正确使用测试用例失败?

2 个答案:

答案 0 :(得分:2)

如果我理解正确的话,我会看到下一个方法:

@Test
public void assertSomethingSuccessTest() {
    // given
    final Object givenActualResult = new Object(); // put your objects here
    final Object givenExpectedResult = new Object(); // put your objects here

    // when
    assertSomething(givenActualResult, givenExpectedResult);

    // then
    // no exception is expected here
}

// TODO: specify exactly your exception here if any
@Test(expected = RuntimeException.class)
public void assertSomethingFailedTest() {
    // given
    final Object givenActualResult = new Object(); // put your objects here
    final Object givenExpectedResult = new Object(); // put your objects here

    // when
    assertSomething(givenActualResult, givenExpectedResult);

    // then
    // an exception is expected here, see annotated expected exception.
}

如果您还需要验证例外:

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

@Test
public void assertSomethingFailedTest() {
    // given
    final Object givenActualResult = new Object(); // put your objects here
    final Object givenExpectedResult = new Object(); // put your objects here

    // and
    thrown.expect(RuntimeException.class);
    thrown.expectMessage("happened?");

    // when
    assertSomething(givenActualResult, givenExpectedResult);

    // then
    // an exception is expected here, see configured ExpectedException rule.
}

答案 1 :(得分:0)

您应该查看Junit 4.7中引入的规则。特别是TestWatcher。

TestWatcher是规则的基类,它注意到测试操作,而不进行修改。例如,此类将记录每次通过和失败的测试:

public static class WatchmanTest {
  private static String watchedLog;

  @Rule
  public TestWatcher watchman= new TestWatcher() {
    @Override
    protected void failed(Throwable e, Description description) {
      watchedLog+= description + "\n";
    }

    @Override
    protected void succeeded(Description description) {
      watchedLog+= description + " " + "success!\n";
     }
  };

  @Test
  public void fails() {
    fail();
  }

  @Test
  public void succeeds() {
  }
}