2017-08-02 93 views
-1

比方说,我创建了我自己的assertSomething(...)方法。我如何编写单元测试来验证它是否正确地使测试用例失败?如何编写自定义JUnit断言的测试?

+0

有用的信息:https://www.guru99.com/junit-assert.html – roottraveller

+0

没有说你不能写一个单元测试它,就像你任何东西。 :-) – cjstehno

+0

很抱歉,这个网页对我的具体问题没有帮助。我正在创建自己的JUnit断言,我想单元测试它的代码。所以我需要测试用例来检查: - 测试用例在我的断言允许时通过 - 测试用例在我的断言不允许时失败。 –

回答

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() { 
    } 
} 
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. 
}