Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing private method using power mock which return list of Integers

I have a private method which take a list of integer value returns me a list of integer value. How can i use power mock to test it. I am new to powermock.Can i do the test with easy mock..? how..

like image 249
user882196 Avatar asked Aug 18 '11 09:08

user882196


3 Answers

From the documentation, in the section called "Common - Bypass encapsulation":

Use Whitebox.invokeMethod(..) to invoke a private method of an instance or class.

You can also find examples in the same section.

like image 169
JB Nizet Avatar answered Nov 20 '22 02:11

JB Nizet


Here is a full example how to do to it:

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.powermock.reflect.Whitebox;

class TestClass {
    private List<Integer> methodCall(int num) {
        System.out.println("Call methodCall num: " + num);
        List<Integer> result = new ArrayList<>(num);
        for (int i = 0; i < num; i++) {
            result.add(new Integer(i));
        }
        return result;
    }
}

 @Test
 public void testPrivateMethodCall() throws Exception {
     int n = 10;
     List result = Whitebox.invokeMethod(new TestClass(), "methodCall", n);
     Assert.assertEquals(n, result.size());
 }
like image 34
Mindaugas Jaraminas Avatar answered Nov 20 '22 00:11

Mindaugas Jaraminas


Whitebox.invokeMethod(myClassToBeTestedInstance, "theMethodToTest", expectedFooValue);
like image 2
Oded Breiner Avatar answered Nov 20 '22 02:11

Oded Breiner