多次重新运行一组JUnit测试

时间:2010-11-11 10:54:59

标签: java junit

我有一组测试测试一些与timzeone相关的功能

我有一个Before方法,它将默认时区设置为我选择的一个,以及一个after方法,可以恢复测试前的默认时间。

所以我基本上想做

将时区设为UTC

运行测试

恢复时区

将时区设为EST

运行测试

恢复时区

将时区设为JST

运行测试

恢复时区

每种情况下的测试都是相同的。

有一种简单的方法吗?

4 个答案:

答案 0 :(得分:5)

是的,有一种很好的方法可以反复进行相同的测试,只需要使用其他一些数据集。解决方案是“@RunWith(Parameterized.class)” - link to javadoc。我假设您正在使用JUnit 4 - 但TestNG也有我记忆中的功能。

您需要编写的代码看起来有点像这样:

 @RunWith(Parameterized.class)
 public class FibonacciTest {
        @Parameters
        public static Collection<Object[]> data() {
                return Arrays.asList(new Object[][] {
                                Fibonacci,
                                { { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 },
                                                { 6, 8 } } });
        }

        private int fInput;

        private int fExpected;

        public FibonacciTest(int input, int expected) {
                fInput= input;
                fExpected= expected;
        }

        @Test
        public void test(@HeresHowYouGetValue Type value) {
                assertAnswerKey(new Object[][] {
                                Fibonacci,
                                { { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 },
                                                { 6, 8 } } });
                assertEquals(fExpected, Fibonacci.compute(fInput));
        }
 }

答案 1 :(得分:1)

我通过使用Parameterized和RunWith符号来解决问题:

请参阅:http://ourcraft.wordpress.com/2008/08/27/writing-a-parameterized-junit-test/

答案 2 :(得分:0)

这是我写的一篇文章,其中显示了使用代码示例重复运行测试的几种方法: http://codehowtos.blogspot.com/2011/04/run-junit-test-repeatedly.html

您可以使用@Parametrized跑步者,或使用帖子中包含的特殊跑步者

答案 3 :(得分:0)

最近我创建了zohhak项目。你会发现它很有用。它让你写:

@TestWith({
   "EST",
   "UTC",
   "null"
})
public void testMethod(TimeZone timeZone) {
   setTimeZone(timeZone);
   ...
}

@After
public void restoreTimezone() {
  ...
}
相关问题