Java 测试类应该只有一个公共零参数构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26672229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:02:02  来源:igfitidea点击:

Test class should have exactly one public zero-argument constructor

javajunitparameters

提问by Md Aslam

I have written a test class, such that is following

我写了一个测试类,如下

public class MyParameterizedClassTest extends BaseRepositoryTest {
    private int multiplierA;
    private int multiplierB;
    public MyParameterizedClassTest(int multiplierA) {
        this.multiplierA = multiplierA;

    }   

    @Parameters
    public static Collection<Object[]> data() { 
        Object[][] data = new Object[][] { { 1 }, { 5 }, { 121 } };
        return Arrays.asList(data);
    }

    @Test
    public void testMultiplyException() {
        assertEquals("Result", multiplierA * multiplierA,multiply(multiplierA));
    }

    public int multiply(int a){
        return a*a;
    }
 }

And My BaseRepositoryTest class is following

我的 BaseRepositoryTest 类正在关注

@RunWith (Parameterized.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public abstract class BaseRepositoryTest extends
    AbstractJUnit4SpringContextTests {



    @Inject
    SessionFactory sessionFactory;

    private Transaction transaction;

    public Session getSession() {
        Session session;
        try {
            session = sessionFactory.getCurrentSession();
        } catch (SessionException se) {
            session = sessionFactory.openSession();
        }
        return session;
    }

    @Before
    public void setUp() throws Exception {
        transaction = getSession().beginTransaction();
    }

    @After
    public void tearDown() throws Exception {
        if (transaction != null) {
            transaction.rollback();
        }
        getSession().close();
    }

    @Before
    public void baseSetUp() {
        MockitoAnnotations.initMocks(this);
    }
}

When I run my test class it shows like,

当我运行我的测试类时,它显示如下,

 Test class should have exactly one public zero-argument constructor:at 
 org.junit.runners.BlockJUnit4ClassRunner.validateZeroArgConstructor

I want to make a test method with @parameters,so please Can anyone please help to find the solution

我想用@parameters 做一个测试方法,所以请任何人都可以帮忙找到解决方案

回答by René Link

I think the problem is that you defined two test runners. One by yourself @RunWith (Parameterized. class)and one that comes with spring, because an AbstractJUnit4SpringContextTestsdefines a @RunWith(SpringJUnit4ClassRunner.class).

我认为问题在于您定义了两个测试运行程序。一个是你自己的@RunWith (Parameterized. class),一个是 Spring 自带的,因为 anAbstractJUnit4SpringContextTests定义了一个@RunWith(SpringJUnit4ClassRunner.class).

Since Junit can only deal with one @RunWithyou can only use @Parameterizedor AbstractJUnit4SpringContextTests. If you want to use both you have to use @Parameterizedand than do the same logic that a SpringJUnit4ClassRunnerdoes on your own.

由于 Junit 只能处理一个,因此@RunWith您只能使用@ParameterizedAbstractJUnit4SpringContextTests。如果您想同时使用两者,则必须使用@Parameterized和执行与 a 相同的逻辑SpringJUnit4ClassRunner

A simple approach can be to just use spring's org.springframework.test.context.TestContextManager.

一个简单的方法可以是只使用 spring 的org.springframework.test.context.TestContextManager.

@RunWith(Parameterized.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public abstract class BaseRepositoryTest extends AbstractJUnit4SpringContextTests {

    private TestContextManager testContextManager;

    @Before
    public void setUpContext() throws Exception {
        this.testContextManager = new TestContextManager(getClass());
        this.testContextManager.prepareTestInstance(this);
    }

}

But this only ensures that the TestExecutionListeners are invoked. Spring normally does a lot more like application context caching and so on. Also a tear down method should be implemented that closes the application context.

但这只能确保TestExecutionListener调用 s。Spring 通常做更多的事情,比如应用程序上下文缓存等等。还应实现关闭应用程序上下文的拆卸方法。

回答by Ezra

If you're running a single test, make sure that you wrote your test class name correctly

如果您正在运行单个测试,请确保您正确编写了测试类名称

A common mistake that I do is to have a class named 'Foo' and a test class named

我犯的一个常见错误是有一个名为“Foo”的类和一个名为的测试类

'FooTest'

'FooTest'

and run a single unit test with

并运行一个单元测试

'Foo'

'福'

instead of 'FooTest'

而不是“FooTest”

If 'Foo' has a public constructor with arguments I get the error:

如果 'Foo' 有一个带参数的公共构造函数,我会收到错误消息:

java.lang.Exception: Test class should have exactly one public zero-argument constructor

回答by tyrantqiao

I have got one answer,it fix on my machine JUnit4 -> when u check the exception

我有一个答案,它修复了我的机器 JUnit4 -> 当你检查异常时

 org.junit.runners.BlockJUnit4ClassRunner.validateZeroArgConstructor(BlockJUnit4ClassRunner.java:171)
 org.junit.runners.BlockJUnit4ClassRunner.validateConstructor(BlockJUnit4ClassRunner.java:148)

get inside to first exception

进入第一个例外

protected void validateZeroArgConstructor(List<Throwable> errors) {
    if(!this.getTestClass().isANonStaticInnerClass() && this.hasOneConstructor() && this.getTestClass().getOnlyConstructor().getParameterTypes().length != 0) {
        String gripe = "Test class should have exactly one public zero-argument constructor";
        errors.add(new Exception(gripe));
    }

}

it will check your constructor is none-parameters or not Try setter injection or field(->field is not recommended officially)

它将检查您的构造函数是否为无参数尝试 setter 注入或字段(官方不推荐 -> 字段)

回答by María Navarro

This error is thrown when your class is not defined as public In your case it is abstract, so it can not be instantiate for testing propouses

当您的类未定义为 public 时会引发此错误在您的情况下它是抽象的,因此无法实例化以进行测试提议

回答by Pruthviraj

Try removing constructor from MyParameterizedClassTestclass.

尝试从MyParameterizedClassTest类中删除构造函数。

I was getting this error when my test class had a public constructor. After removing, it started working.

当我的测试类有一个公共构造函数时,我收到了这个错误。删除后,它开始工作。

回答by s1m0nw1

JUnit 4 vs 5 (Jupiter)

JUnit 4 与 5(木星)

I had this issue when I imported the wrong Testimplementation. while my constructor was using JUnit 5 features, I imported the old org.junit.Testrather than org.junit.jupiter.api.Test.

当我导入错误的Test实现时,我遇到了这个问题。当我的构造函数使用 JUnit 5 特性时,我导入了旧的org.junit.Test而不是org.junit.jupiter.api.Test.