1

我正在尝试创建一个Junit测试套件以及使用,PowerMockRunner但它不起作用。

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(MainTest.class)
@Suite.SuiteClasses({ MainTest.Class1Test.class })
@PrepareForTest({
    StaticFieldsProvider.class
})
public class MainTest extends Suite {

public MainTest(Class<?> klass, RunnerBuilder builder)
        throws InitializationError {
    super(klass, builder);
}

public static class TestBase {
    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        PowerMockito.mockStatic(StaticFieldsProvider.class);
    }
}

public static class Class1Test extends TestBase {
    @Before
    public void setUp() {
        super.setUp();
    }

    @Test
    public void test(){
        assertTrue(true);
    }
 }
}

当我尝试运行时,它失败并出现错误 -

java.lang.IllegalArgumentException:测试类在 org.junit.runners.model.TestClass.(TestClass.java:40) 只能有一个构造函数

关于如何PowerMockRunner在上述情况下使用的任何建议?

谢谢

4

2 回答 2

0

This is an old question, so we may get no resolution on whether or not this solution works for the OP; but this might work (I can't verify without having access to StaticFieldsProvider, but it works if I swap that out with one of my own classes). I would love for someone to edit and add more explanation as to why this works:

@RunWith(PowerMockRunner.class)
// * Delegate to Suite.class instead of MainTest.class *
@PowerMockRunnerDelegate(Suite.class)
@Suite.SuiteClasses({ MainTest.Class1Test.class })
@PrepareForTest({
        StaticFieldsProvider.class
})
// * Don't extend Suite *
public class MainTest {

// * Remove constructor *

    public static class TestBase {
        @Before
        public void setUp() {
            MockitoAnnotations.initMocks(this);
            PowerMockito.mockStatic(StaticFieldsProvider.class);
        }
    }

    public static class Class1Test extends TestBase {
        @Before
        public void setUp() {
            super.setUp();
        }

        @Test
        public void test(){
            assertTrue(true);
        }
    }
}

In case it helps someone else, I had a slightly different scenario in that only a couple of the classes in my suite need PowerMockRunner (and don't mock out the same thing, so the mock needs to happen in each individual test class instead of in the runner). It appears that as long as I @PrepareForTest in my runner (as above) the classes I will need in some of the test classes, I can still create the mocks in the @Before (or wherever) of the applicable test class. Hope this helps.

于 2019-06-03T16:53:30.563 回答
-1

您不能扩展Suite,因为这是 JUnit 3 的一部分并且您正在使用 JUnit 4。(删除和 构造函数。)有关JUnit 4 中的套件的更多数据,extends请参阅JUnit Wiki 。

于 2015-09-08T16:30:24.257 回答