lundi 1 juillet 2019

Use Reflection to Write test for private methods

I have a class that is NetworkManager. I have a lot of private methods that I realy need to write test for them.

At first I didn't find any solution to write test for my private methods. Anyway I find a way to access my private methods and write some test for them.

I used Reflection to access my functions and write tests for them. there is an example of a simple private method:

 private String myFun (String input){
        return input+"hello";
    }

There is a test class that I used reflection in it:

@RunWith(AndroidJUnit4.class)
public class NetworkManagerTest {

    private static NetworkManager networkManager;
    private Context appContext = InstrumentationRegistry.getTargetContext();

    private @ADType
    int adType = ADType.TYPE_BANNER;


    @BeforeClass
    public static void setup() {

        getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {

                networkManager = NetworkManager.getInstance();
                networkManager.addNetworkCall(TestUtil.getSampleSystemRequest());

            }
        });
    }

    @Test
    public void sample() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Method method = NetworkManager.class.getDeclaredMethod("myFun", String.class);
        method.setAccessible(true);
        String output = (String) method.invoke(networkManager, "Ehsan");

        Assert.assertEquals("Ehsanhello", output);
    }

}

This is works fine. But the question is how much is this way okay to write test for private methods with using of reflection?

Is there a better way to achieve this goal?

Aucun commentaire:

Enregistrer un commentaire