【问题标题】:How to write a test for custom JUnit assertion?如何为自定义 JUnit 断言编写测试?
【发布时间】:2017-08-02 15:44:59
【问题描述】:

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

【问题讨论】:

  • 没有什么说你不能像其他任何东西一样为它编写单元测试。 :-)
  • 不幸的是,这个页面对我的具体问题没有帮助。我正在创建自己的 JUnit 断言,我想对其代码进行单元测试。所以我需要有测试用例来检查: - 当我的断言允许时测试用例通过 - 当我的断言不允许时测试用例失败。

标签: unit-testing junit assertion


【解决方案1】:

如果我理解正确,我会看到下一条:

@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.
}

【讨论】:

    【解决方案2】:

    您应该查看在 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() {
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2021-02-03
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多