简体   繁体   English

没有默认构造函数和私有方法的Abstract类的测试类?

[英]Test class for Abstract class with no default constructor and private method?

I have got a problem in my project and I'm putting up my problem in some sample example. 我的项目有问题,我在一些示例中提出了问题。

package com.sample.code;

public abstract class AbstractClass {

    public String var1;

    //in this class NO default constructor

    public String method1(){
        return "method1 "+privateMethod();
    }

    protected AbstractClass(String var1){
        this.var1=var1;
    }

    private String privateMethod(){
        return "private method";
    }
}

I have got a private method that is used by my actual method and a protected single argumented constructor. 我有一个私有方法供我的实际方法和一个受保护的单参数构造函数使用。

I need to write test case for my ' method1() '. 我需要为“ method1() ”编写测试用例。
I need to use junit and EasyMock. 我需要使用junit和EasyMock。

Test class is also a typical java class, it can extend other classes, even tested class, so you can do this: 测试类也是典型的java类,它可以扩展其他类,甚至是测试过的类,因此您可以执行以下操作:

class AbstractClassTest extends AbstractClass
{
    public AbstractClassTest()
    {
        super("some_string");
    } 
    @Test
    public void testMethod1()
    {
         //....
    }
}

Since test class is extending base class you have to call in it's constructor the base class constructor. 由于测试类是扩展基类,因此必须在其构造函数中调用基类构造函数。 You don't have setter for this private field, so if you will need to test more instances you can instantiate test class inside test class: 您没有此私有字段的设置器,因此,如果您需要测试更多实例,则可以在测试类中实例化测试类:

AbstractClassTest abc = new AbstractClassTest("other_string");

To do this you will need second ctor for test class: 为此,您将需要第二个ctor用于测试类:

public AbstractClassTest(String param)
{
    super(param);
}

I would test it using concrete class implementation like: 我将使用如下的具体类实现对其进行测试:

 MyConcreteClass clazz = ..;//MyConcreteClass could be local class or actual production class
 Assert.assertEquals("method1 private method",clazz.method1());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM