简体   繁体   中英

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() '.
I need to use junit and EasyMock.

Test class is also a typical java class, it can extend other classes, even tested class, so you can do this:

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:

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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