简体   繁体   中英

(Java)TestNG/Junit -How to Unit test a protected method in a class with no zero-argument-constructor?

I have a class

Class abc extends base {
public abc(String a, String b)
{
super(a,b);
}

@Override
protected Object fun(String a)
{Object x;
doSomething;
return x;
}}

Note: There is no Zero-Argument Constructor for this class.

I am supposed to add a Unit test for the function fun(..). Is it possible using -TestNG/JUnit/Mockito ?

You can create an object using the non-zero-argument constructor and unit-test the protected method if your unit test sits in the same package as the class.

If it's absolutely necessary to suppress the constructor, PowerMock can do it.

I already found a solution. I created a test class:

public class testAbc extends abc {
public testAbc()
{super("x","y");}
@Override
public Object fun(String a){
Object x = super.fun(a);
}

@Test
public void testFun()
{
TestAbc t = new TestAbc();
t.fun("testString");
}


}

create a default constructor in the test class and make the Overridden function public.

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