Spring错误——Test class should have exactly one public constructor
- 背景:Spring 构建单元测试
- 错误
java.lang.Exception: Test class should have exactly one public constructor at org.junit.runners.BlockJUnit4ClassRunner.validateOnlyOneConstructor(BlockJUnit4ClassRunner.java:131) at org.junit.runners.BlockJUnit4ClassRunner.validateConstructor(BlockJUnit4ClassRunner.java:120) at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:101) at org.junit.runners.ParentRunner.validate(ParentRunner.java:344) at org.junit.runners.ParentRunner.<init>(ParentRunner.java:74) at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55) at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:13)
- 错误原因:在Junit测试类中必须声明一个public 构造函数。我的测试类没有声明public,默认为default 。
public class TestBeanScope extends UnitTestBase { TestBeanScope(){ super("classpath*:spring-scope.xml"); } @Test public void TestSingleton(){ for (int i=0;i<3;i++){ BeanScope beanScope = (BeanScope)super.getBean("beanScope"); beanScope.say("test"); } } }
- 解决办法:构建一个公有构造函数即可
public class TestBeanScope extends UnitTestBase { public TestBeanScope(){ super("classpath*:spring-scope.xml"); } @Test public void TestSingleton(){ for (int i=0;i<3;i++){ BeanScope beanScope = (BeanScope)super.getBean("beanScope"); beanScope.say("test"); } } }
- Next