How to create a JUnit 4 test suite to pass when expected exceptions are thrown

主宰稳场 提交于 2019-12-14 01:20:43

问题


I am writing a JUnit 4 test suite which runs some tests that check if an exception has been thrown. On their own, my tests look somewhat like this:

@RunWith(value=BlockJUnit4ClassRunner.class)
public class CreateCommandsExceptionsTest extends TestCase {
    Statistics statistics;
    @Before
    public void setUp(){
        ...
    }
        ...
    @Test (expected=StatsArrayTooShortException.class)
    public void testStatsArrayTooShortException(){
        ...
    }

The tests run fine on their own, but when I attempt to put them in a test suite, they fail because the exception that I am testing for is being thrown.

My test suite looks like:

@RunWith(value=BlockJUnit4ClassRunner.class)
public class UnitTestSuite {
public static testSuite(){
    TestSuite suite = new TestSuite("Test for unitTests");

    suite.addTestSuite(StatisticsTest.class);
    ...
    return suite;
}
}

If anyone could tell me how I should be setting up my test suite so that I can pass a test when I catch an expected exception, I would appreciate it.


回答1:


You are using the wrong syntax for Suites in Junit 4.

This is the right way:

@RunWith(Suite.class)
@Suite.SuiteClasses({
        JunitTest1.class,
        JunitTest2.class
})
public class JunitTest5 {
}


来源:https://stackoverflow.com/questions/5536448/how-to-create-a-junit-4-test-suite-to-pass-when-expected-exceptions-are-thrown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!