Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a private method [duplicate]

I have a method which is private . Now, I do not want to call this private method while doing unit test on execute() method. I have tried with PowerMockito and all, but with all type of mockings it still enter into the private method.

Please suggest with workable testcase. Would appreciate the same.

@Component 
public class Employee implements SuperClass {

    @Autowired
    private FileTraverse fileTraverse;

    @Override 
    public void execute() throws Exception {
        List<String> traverse = fileTraverse.getFiles();
        Boolean t = isFileTraversed(traverse);
    } 

    private Boolean isFileTraversed(List<String> param1) {
        Boolean flag;
        //do some DB operation and return flag;
    }
}
like image 305
user3336194 Avatar asked Dec 31 '25 08:12

user3336194


1 Answers

Don't mock private methods.

See the suggestion below:

@Component 
public class Employee implements SuperClass {

    @Autowired
    private FileTraverse fileTraverse;

    @Override 
    public void execute() throws Exception {
        List<String> traverse = fileTraverse.getFiles();
        Boolean t = isFileTraversed(traverse);
    } 

    private Boolean isFileTraversed(List<String> param1) {
        Boolean flag;
        //do some DB operation and return flag;
    }
}

So inside isFileTraversed - you will have a DB operation. This operation will probably be executed through a DAO/Repository object.

So your code will probably look like:

@Component 
public class Employee implements SuperClass {

    @Autowired
    private FileTraverse fileTraverse;

    @Autowired
    private DatabaseAccessDao dbAccess;

    @Override 
    public void execute() throws Exception {
        List<String> traverse = fileTraverse.getFiles();
        Boolean t = isFileTraversed(traverse);
    } 

    @Override
    private Boolean isFileTraversed(List<String> param1) {
        Boolean flag;
        flag = dbAccess.checkFileTraversed(param1);
        return flag;
    }
}

What you need to do is to mock the public checkFileTraversed() method on the DatabaseAccessDao class.

1) Don't @Autowire on fields - prefer constructor injection.

2) Are you sure you want to return a Boolean? Is "null" allowed as a return value? If not - consider using the primitive boolean type;

like image 131
hovanessyan Avatar answered Jan 03 '26 10:01

hovanessyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!